输出复制的字符串困难

Trouble outputting a copied string

本文关键字:字符串 复制 输出      更新时间:2023-10-16

这已经为我带来了一段时间的麻烦,而我对代码的调整似乎有所作为。我试图在文件中读取的文本行中找到数字,然后将数字存储到另一个字符串中,以后要使用。初始复制似乎很成功,但是当尝试输出字符串数字存储在中时,唯一的输出是空白行。

这是代码,包含标头文件:

#include<iostream>
#include<string>
#include<fstream>
#include<cctype>
using namespace std;
int main()
{
    ifstream inFile;
    string temp;
    short count = 0;
    char fileName[20];  
    string info1;
    cout << "Enter the name of the file to be used: " << endl;
    cin >> fileName;
    inFile.open(fileName);
    if(!inFile)
    {
        cout << "Error opening file." << endl;      
    }
    else
    {           
        getline(inFile, info1);
        cout << info1 << endl;
        for(short i = 0; i < info1.length(); i++)
        {
            if(isdigit(info1[i]))
            {   
                temp[count] = info1[i];
                cout << temp[count] << endl;
                count++;
            }
        }
        cout << temp << endl;
    }   
    inFile.close();
    return 0;
}

,输出如下:

Enter the name of the file to be used:
input.txt
POPULATION SIZE: 30
3
0

显然,它不会按预期输出 temp 。任何帮助或建议将不胜感激。

问题是 temp不是简单的char数组。它是std::string类。最初temp是空的。这意味着我们不知道为字符串分配了多少内存。它甚至可以为0。因此,当您使用用于空字符串的std::string::operator[]时,请参考应返回哪个符号?

您应该使用std::string::operator+=或Char数组。

实际上,它 di d di 输出 temp值 - 只有此值是一个空字符串。考虑一下:

  string str = "A";
  for (int i=0; i < 2; i++)
  {
    str[i] = 'B';  
    cout << str[i] << endl;
  }
  cout << "And the final result is..." << str;

这将输出两个B s(通过内部循环的cout),但最终结果的字符串将仅是一个B。原因是operator[]不会"展开"字符串 - 它可以用作替换该字符串字符的字符串的设置,而仅用于已经在字符串中的索引:它不会在该字符串中分配该字符串的其他内存索引溢出的情况。

因此,要构建字符串,您可以使用另一个操作员-+=(串联分配):

  string str;
  for (int i=0; i < 2; i++)
  {
    str += 'B';  
    cout << str[i] << endl;
  }
  cout << "And the final result is..." << str;

将打印BB作为最终结果。

使用此,
temp+=info1[i];
而不是
temp[count] = info1[i];