2011-03-06 62 views
1

我是C++的新手,我试图编写一个简短的C++程序,用于从文件中读取 文本行,每行包含一行整数键和一个字母数字字符串值(不嵌入空格)。行数不是预先知道的(即保持读行直到文件结束)。该程序需要使用'std :: map'数据结构来存储从输入读取的整数和字符串(并将整数与字符串关联)。程序然后需要输出字符串值(但不是整数值)到标准输出,每行1个,按整数键值(从小到大)排序。因此,举例来说,假设我有一个名为 “data.txt中”,其中包含以下三行的文本文件:从.txt文件中读取字符串和整数并仅以字符串形式打印输出

10狗
-50马
0猫
-12斑马
14海象

输出应该然后是:


斑马


个 海象

我下面粘贴到目前为止,我已在我的C进度++程序:

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

不幸的是,这将产生以下不正确的输出:



zebra
海象

如果任何人有任何提示,提示,建议等等 我需要让程序根据需要让它工作,请问 让我知道吗?

谢谢!

+1

请标记功课功课。 – Erik 2011-03-06 23:32:16

+1

“使用'std :: map'数据结构来存储从输入读取的整数和字符串(以及将整数与字符串关联)”的部分在哪里? – HighCommander4 2011-03-06 23:32:29

+0

另外请注意,您应该在返回main()函数之前调用close()方法。 – Bv202 2011-03-06 23:39:45

回答

1

您遇到问题是因为您尝试每次读取两行:第一次使用getline,然后使用操作符>>。

0

你根本没有在任何方面实际使用过std::map。您需要将整数/字符串对插入到映射中,然后将其作为输出进行迭代。并且没有必要close()流。

+0

我不知道为什么这是downvoted:其他答案根本没有提到“该程序需要使用'std :: map'数据结构”的先决条件。 – 2013-11-14 08:23:22

2

看到它:

#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; 
}