簡體   English   中英

從.txt文件中讀取字符串和整數並僅將輸出打印為字符串

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

我是C ++的新手,我正在嘗試編寫一個簡短的C ++程序,該程序從文件中讀取文本行,每行包含一個整數鍵和一個字母數字字符串值(無嵌入式空格)。 行數是事先未知的(即保持讀取行數直到到達文件末尾)。 該程序需要使用'std :: map'數據結構來存儲從輸入中讀取的整數和字符串(並使整數與字符串相關聯)。 然后,程序需要將字符串值(但不是整數值)輸出到標准輸出,每行1個,按整數鍵值(最小到最大)排序。 因此,例如,假設我有一個名為“ data.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();
}

不幸的是,這會產生以下錯誤輸出:



斑馬
海象

如果有人對我需要對該程序進行的更改和修訂有任何提示,提示,建議等,以使其能夠按需運行,您能告訴我嗎?

謝謝!

看見:

#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 >>。

實際上,您根本沒有使用過std::map 您需要將整數/字符串對插入到映射中,然后對其進行迭代作為輸出。 並且不需要close()流。

代替使用“!myfile.eof()”,使用此代碼將有所幫助。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM