How do I get an input file to read into a string array in C++?

爱⌒轻易说出口 提交于 2019-12-12 04:23:52

问题


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();

回答1:


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

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

getline(inputFile, track);

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.




回答2:


Your loop is using the operator>> to read the file into the array. That operator reads one word at a time. You need to remove that operator completely and use std::getline() to fill the array, eg:

const int numTracks = 25;
std::string tracks[numTracks];
int count = 0;

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

std::ifstream inputFile;
inputFile.open("SetList.txt");
while (count < numTracks)
{
    if (!std::getline(inputFile, tracks[count])) break;
    count++;
}
inputFile.close();

Or:

const int numTracks = 25;
std::string tracks[numTracks];
int count = 0;

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

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

Alternatively, consider using a std::vector instead of a fixed array, then you can use std::istream_iterator and std::back_inserter to get rid of the manual loop completely:

class line : public std::string {}

std::istream& operator>>(std::istream &is, line &l)
{   
    return std::getline(is, l);
}

...

std::vector<std::string> tracks;

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

std::ifstream inputFile;
inputFile.open("SetList.txt");

std::copy(
    std::istream_iterator<line>(inputFile),
    std::istream_iterator<line>(),
    std::back_inserter(tracks)
);

inputFile.close();


来源:https://stackoverflow.com/questions/38602495/how-do-i-get-an-input-file-to-read-into-a-string-array-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!