2013-03-24 160 views
1

我正在用C++編寫一個小程序,並有一個輸入文件,需要逐行閱讀,文件中有2列,字符串名稱和整數。例如:閱讀來自txt文件的2列

abad 34 
alex 44 
chris 12 

我寫這樣的代碼:

ifstream input("file.txt"); 
int num; 
string str; 

while(getline(input, line)){ 
    istringstream sline(line); 
    if(!(sline>>str>>num)){ 
    //throw error 
    } 
    ... 
} 

我需要的情況下拋出錯誤:

如果沒有號碼 - 只有名字寫例如abad(我的代碼實際上我收到提示),

,如果有一個名字,沒有號碼,如:abad 34a(在34a字母被忽略,並且轉移到恰好34在我的代碼,而錯誤應該被觸發)

或者如果超過2列eg abad 34 45(第二個數字被忽略)。

如何正確讀取輸入數據(並且沒有迭代器)?

回答

2

試試這個:

if(!(sline >> str >> num >> std::ws) || sline.peek() != EOF) { 
    //throw error 
} 

std::ws是一個流處理器,其提取如下num可能的空白。包括<iomanip>。接下來,檢查流中的窺視是否返回EOF。如果沒有,你有更多的輸入等待,這是一個錯誤。

+0

不幸的是這個解決方案沒有奏效,對於'阿巴德34a'我仍然沒有錯誤,並獲得數34 – NGix 2013-03-24 11:32:16

+0

@ Ir0nm哎呀,我的邏輯很爛:)應該是'||'而不是'&&'。固定。 – jrok 2013-03-24 11:50:35

+0

是的,你是對的)它現在的作品,並非常感謝優雅的解決方案 – NGix 2013-03-24 11:56:18

1

請嘗試以下操作:繼續使用std::vector在每行中讀取所有字符串,以便您可以更輕鬆地處理它們。然後,有三種情況:

  • 否數量:vec.size()= 1
  • 兩個以上的字符串:vec.size()> 2.
  • 無效的號碼:並不是所有的VEC的數字[1]是數字

代碼:

#include <fstream> 
#include <sstream> 
#include <string> 
#include <vector> 
#include <cstdlib> 
#include <cctype> 

using namespace std; 

int main() { 
    fstream in("input.txt", fstream::in); 
    fstream out("error.txt", fstream::out); 

    string line; 

    while(getline(in, line)) { 
    vector<string> cmd; 
    istringstream istr(line); 
    string tmp; 

    while(istr >> tmp) { 
     cmd.push_back(tmp); 
    } 

    if(cmd.size() == 1) // Case 1: the user has entered only the name 
    { 
     out << "Error: you should also enter a number after the name." << endl; // or whatever 
     continue; // Because there is no number in the input, there is no need to proceed 
    } 
    else if(cmd.size() > 2) // Case 3: more than two numbers or names 
    { 
     out << "Error: you should enter only one name and one number." << endl; 
    } 

    // Case 2: the user has enetered a number like 32a 

    string num = cmd[ 1 ]; 

    for(int i = 0; i < num.size(); ++i) { 
     if(!isdigit(num[ i ])) { 
     out << "Error: the number should only consist of the characters from 1-9." << endl; 
     break; 
     } 
    } 
    } 

    return 0; 
} 

文件:input.txt中

abad 34 
alex 44 
chris 12 
abad 
abad 24a 
abad 24 25 

文件:error.txt

Error: you should also enter a number after the name. 
Error: the number should only consist of the characters from 1-9. 
Error: you should enter only one name and one number.