输出复制的字符串困难
Trouble outputting a copied string
这已经为我带来了一段时间的麻烦,而我对代码的调整似乎有所作为。我试图在文件中读取的文本行中找到数字,然后将数字存储到另一个字符串中,以后要使用。初始复制似乎很成功,但是当尝试输出字符串数字存储在中时,唯一的输出是空白行。
这是代码,包含标头文件:
#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];
相关文章:
- 使用 strcpy_s 将字符串复制到字符*
- 在这种情况下,使用 string_view 是否会导致不必要的字符串复制?
- 无法使用 strcpy 将字符串复制到静态结构成员
- 我的 c 字符串复制函数正在损坏其他变量的堆栈
- 将 C 样式字符串复制到免费存储上分配的内存中
- strcpy_s将超过字符串长度的字符串复制到目标缓冲区(用 0xFE 填充)
- 将字符串复制到类中的常量字符
- 使用 copy_if 复制 std::字符串(复制到另一个字符串中)
- 将字符串复制到C 中的另一个字符串并打印其字符
- Linux/C++ 将字符串复制到剪贴板
- 将字符串复制到 char* 的现代C++方法
- 从一个字符串复制到另一个字符串并粘贴到新文件中
- 如何才能将字符串复制到带有 std::string 字段的结构中
- 如何将数字列表从字符串复制到C++向量
- 通过指针将字符串复制到结构
- 如何将包含多个空字符的字符串复制到字符串流
- 为什么我不能从字符串复制初始化字符串流?
- 如何做字符串::复制C++的反义词
- 即使在将新字符串复制到现有字符串之后,旧包含也可用(在某些索引中)
- c无法将字符串复制到文件中