如何读取n至n+我在c++中排行榜
这是要读的文件
5 name1 name2 name3 名称4 名称5
我当前阅读的代码是:
void readData(string fileName, string names[], int n) {
ifstream myFile("file.txt");
string line;
if (myFile.is_open())
{
myFile >> n; // read first line
cout << n;
for (int i = 0; i < n; ++i) {
getline(myFile, line);
names[i] = line;
cout << names[i] << endl;
}
}
}
我想将名称放入数组名称[],但是即使n = 5,它似乎只运行4次。这是为什么?
这是我目前得到的输出:
5
Name1
Name2
Name3
Name4
This is the file to be read
5 Name1 Name2 Name3 Name4 Name5
My current code to read this is:
void readData(string fileName, string names[], int n) {
ifstream myFile("file.txt");
string line;
if (myFile.is_open())
{
myFile >> n; // read first line
cout << n;
for (int i = 0; i < n; ++i) {
getline(myFile, line);
names[i] = line;
cout << names[i] << endl;
}
}
}
I want to put the names into the array names[], but even though n = 5, it seems like it runs only 4 times. Why is that?
This is my current output that I get:
5
Name1
Name2
Name3
Name4
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您做
myfile&gt;&gt;时,您没有阅读整行。 n
。因此,第一个getline只是阅读该行的其余部分,这是空的
或
You didnt read the whole first line when you did
myFile >> n
. So the first getline just read the rest of that line, which is emptyDo
or