简体   繁体   中英

Reading strings and integers from .txt file and printing output as strings only

I'm new to C++, and I'm trying to write a short C++ program that reads lines of text from a file, with each line containing one integer key and one alphanumeric string value (no embedded whitespace). The number of lines is not known in advance, (ie, keep reading lines until end of file is reached). The program needs to use the 'std::map' data structure to store integers and strings read from input (and to associate integers with strings). The program then needs to output string values (but not integer values) to standard output, 1 per line, sorted by integer key values (smallest to largest). So, for example, suppose I have a text file called "data.txt" which contains the following three lines:

10 dog
-50 horse
0 cat
-12 zebra
14 walrus

The output should then be:

horse
zebra
cat
dog
walrus

I've pasted below the progress I've made so far on my C++ program:

#include <fstream>  
#include <iostream>  
#include <map>
using namespace std;
using std::map;
int main () 
{
string name;
signed int value;
ifstream myfile ("data.txt");

while (! myfile.eof() )
{
getline(myfile,name,'\n');
myfile >> value >> name;
cout << name << endl;
}
return 0;
myfile.close();
}

Unfortunately, this produces the following incorrect output:

horse
cat
zebra
walrus

If anyone has any tips, hints, suggestions, etc. on changes and revisions I need to make to the program to get it to work as needed, can you please let me know?

Thanks!

See it:

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main()
{
        string name;
        int value;
        ifstream myfile("text.txt", ifstream::in);
        while(myfile >> value >> name)
                cout << name << endl;
        return 0;
}

您遇到了问题,因为您尝试两次读取每一行:首先使用getline,然后使用operator >>。

You haven't actually used std::map in any regard, at all. You need to insert the integer/string pair into the map, and then iterate over it as the output. And there's no need to close() the stream.

Instead of using "! myfile.eof()" use this code it will help.

ifstream is;
string srg;
is.open(filename);
 while(getline(is,srg))
 {//your code
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM