这已经给我带来了一段时间的麻烦,我对代码所做的任何调整似乎都没有什么不同。 我试图在从文件中读取的一行文本中找到数字,并将所述数字存储到另一个字符串中以备后用。最初的复制似乎是成功的,但是当尝试输出存储数字的字符串时,唯一的输出是一个空行。
这是代码和包含的头文件:
#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
不是简单的字符数组。它是 std::string
类。最初 temp
是空的。这意味着我们不知道为字符串分配了多少内存。它甚至可以是 0。因此,当您将 std::string::operator[]
应用于空字符串时,请引用应该返回什么符号?
您应该改用 std::string::operator+=
或 char 数组。
关于c++ - 输出复制的字符串时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13208900/