如何获取输入文件以读取C ++中的字符串数组? [英] How do I get an input file to read into a string array in C++?

查看:208
本文介绍了如何获取输入文件以读取C ++中的字符串数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于某种原因,我输入文件中的全行未读入数组,仅读入了每行的第一个单词。我目前正在使用getline调用,但是我不确定为什么它不起作用。这是我要填充数组的调用。 txt文件是歌曲列表。

For some reason the full lines from my input file are not reading into the array, only the first word in each line. I am currently using the getline call, but I am not sure why it is not working. Here is the what I have for the call to populate the array. The txt file is a list of songs.

const int numTracks = 25;
string tracks[numTracks];
int count = 0, results;
string track, END;

cout << "Reading SetList.txt into array" << endl;

ifstream inputFile;
inputFile.open("SetList.txt");
while (count < numTracks && inputFile >> tracks[count])
{
    count++;
    getline(inputFile, track);
}
inputFile.close();


推荐答案

while (count < numTracks && inputFile >> tracks[count])

The >> 运算符读取单个单词。

The >> operator reads a single word. And this code reads this single word into the vector in question.

getline(inputFile, track);

是的,您使用的是 getline()。将第一个单词后的其余行读入一个不相关的变量,称为 track track 似乎是非常无聊的 std :: string ,显然在循环的每次迭代中都会被覆盖,否则将被完全忽略。

True, you're using getline(). To read the rest of the line, after the initial word, into some unrelated variable called track. track appears to be a very bored std::string that, apparently, gets overwritten on every iteration of the loop, and is otherwise completely ignored.

这篇关于如何获取输入文件以读取C ++中的字符串数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆