【发布时间】:2020-04-07 22:10:41
【问题描述】:
我尝试使用动态字符串数组来制作它,但是当我尝试添加 2 行时,它只添加了 1 行,我不知道为什么 这是我的代码
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
int x;
string name;
string* lines;
cout << "Input the file name to be opened : ";
cin >> name;
cout << endl << "Input the number of lines to be written : ";
cin >> x;
lines = new string[x];
cout << endl << "The lines are :";
for (int i = 0; i < x; i++)
{
getline(cin,lines[i]);
}
fstream File(name, ios::out | ios::app);
for (int i = 0; i < x; i++)
{
File << lines[i] << endl;
}
File.close();
}
它给了我这个警告: C6385 从 'lines' 读取无效数据:可读大小为 '(unsigned int)*28+4' 字节,但可能读取 '56' 字节
【问题讨论】:
-
不用担心,使用
std::vector<std::string>。它将减轻您遇到的问题。 -
或者,只需在阅读文件时将每一行附加到文件(在输入循环中)。该程序显然不需要将所有行存储在内存中。
-
另请注意,在
cin >> x之后,整数输入后面的任何额外空格或字符(包括换行符)仍将是未读的。当您调用getline时,这些字符将构成第一行,因此如果您输入一个数字并按 Enter,则读取的第一行将为空。 -
请注意,以上内容并不意味着在您的代码周围撒上“以防万一”
cin.ignore()s。如果您需要ignore,请在将您需要的内容留在流中的操作之后执行。如果您在读取之前抢先放置ignore,迟早您会发现没有您想要忽略的任何内容,而是您不小心删除了您确实想要的输入。 -
@user4581301 @paddy 正如你们俩所说我尝试在
getline之前使用cin.ignore()它仅适用于第一行,但它从第二行删除了一个字母,所以我使用此代码` (int i = 0; i
标签: c++