C++ 从.txt文件中读取字符串和整数,并仅以字符串形式打印输出 >值>>名称; 您可能会遇到问题,因为您尝试读取每一行两次:首先使用getline,然后使用operator>>。

C++ 从.txt文件中读取字符串和整数,并仅以字符串形式打印输出 >值>>名称; 您可能会遇到问题,因为您尝试读取每一行两次:首先使用getline,然后使用operator>>。,c++,C++,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.

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();
}
#包括
#包括
#包括
使用名称空间std;
使用std::map;
int main()
{
字符串名;
符号整数值;
ifstream myfile(“data.txt”);
而(!myfile.eof())
{
getline(myfile,名称,'\n');
myfile>>值>>名称;

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

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

查看它:

#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;
}
#包括
#包括
#包括
使用名称空间std;
int main()
{
字符串名;
int值;
ifstream myfile(“text.txt”,ifstream::in);
while(我的文件>>值>>名称)
cout不要使用“!myfile.eof()”使用此代码,它会有所帮助

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

请将家庭作业标记为家庭作业。您“使用'std::map'数据结构存储从输入读取的整数和字符串(并将整数与字符串关联)”的部分在哪里?还请注意,您应该在返回main()之前调用close()-方法-函数。@Bv202:甚至不需要关闭文件,由
ifstream
析构函数处理。我不知道为什么会被否决:其他答案根本没有提到“程序需要使用'std::map'数据结构”的先决条件。