我试图使用动态字符串数组来制作它,但是当我尝试添加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从“行”中读取无效数据:可读大小为“(无符号整数)* 28 + 4”字节,但可以读取“ 56”字节
答案 0 :(得分:2)
要存储您的字符串,可以使用std::vector
,它是一个可变大小的C ++容器,比C类型的数组更受欢迎,这是带有注释的示例:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <limits>
using namespace std; //for test purposes, in real code you shoud use std:: scope
int main()
{
int x;
string name, line;
vector<string> lines; //container
cout << "Input the file name to be opened : ";
cin >> name;
fstream File(name, ios::app | ios::out);
cout << endl
<< "Input the number of lines to be written : ";
cin >> x;
cin.ignore(numeric_limits<streamsize>::max(), '\n'); //needed because getline does not ignore new line characters
//explicitly looking to clear buffer till '\n', improves clarity
cout << endl
<< "The lines are :";
while (x > 0)
{
getline(cin, line);
lines.push_back(line); //add lines to vector, this is assuming you need the lines in memory
x--; //otherwise you could save them directly to the file
}
if (File.is_open())
{
for (string s : lines) //writing all the lines to file
{
File << s << endl;
}
File.close();
}
}