簡體   English   中英

c ++如何讀取流直到行尾

[英]c++ how to read stream till end of line

我想從文件中讀取這樣的輸入

球3 3 3 4
金字塔2 3 4 12 3 5 6 7 3 2 4 1 2 3
矩形2 3 4 1 9 12

我想做這樣的事情

char name[64];  
int arr[12];  
ifstream file (..);  
while(file)  
{   
file >> name;  
    while( //reach end of line) 
        file >> arr[i]
}

正如您所看到的,我不知道將輸入多少個整數,這就是我想要停在新線上的原因。 我用getline完成了它,然后分割線,但是他們告訴我只能用>> operator來完成。

注意:我不能使用std::stringstd::vector

簡單的版本是使用類似於std::ws的操縱符,而不是在遇到換行符時跳過所有空格設置std::ios_base::failbit 然后將使用此操縱器而不是隱式跳過空格,而不是跳過新行。 例如(代碼不是測試,但我認為這樣的東西,刪除了錯誤和編譯錯誤應該工作):

std::istream& my_ws(std::istream& in) {
    std::istream::sentry kerberos(in);

    while (isspace(in.peek())) {
        if (in.get() == '\n') {
            in.setstate(std::ios_base::failbit);
        }
    }
    return in;
}
// ...
char name[64];
int  array[12];
while (in >> std::setw(sizeof(name)) >> name) {  // see (*) below
    int* it = std::begin(array), end = std::end(array);
    while (it != end && in >> my_ws >> *it) {
        ++it;
    }
    if (it != end && in) { deal_with_the_array_being_full(); }
    else {
        do_something_with_the_data(std::begin(array), it);
        if (!in.eof())  { in.clear(); }
    }
}

我的個人猜測是,賦值要求將值讀入char數組,然后使用atoi()strol() 我認為這對練習來說是一個無聊的解決方案。

(*) 不要 ,甚至沒有在〔實施例的代碼,使用帶有格式的輸入操作char數組array 不能設置允許的最大大小! 可以通過設置流的width()來設置大小,例如,使用操縱器std::setw(sizeof(array)) 如果使用帶有char數組的格式化輸入運算符時width()0 ,則讀取任意數量的非空白字符。 很容易溢出陣列,成為安全問題! 從本質上講,這是拼寫C的gets()的C ++方式(現在從C和C ++標准庫中刪除)。

我想你可以使用peek方法:

while (file)
{
    file >> name;
    int i = 0;
    while(file.peek() != '\n' && file.peek() != EOF) {
        file >> arr[i++];
    }
}

暫無
暫無

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

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