簡體   English   中英

從無組織的文本文件中讀取整數

[英]Reading integers from an unorganized text file

#include <iostream>
#include <fstream>
#include <string>
#include <cctype> // isdigit();
using namespace std;
int main()
{
    ifstream fin;
    fin.open("Sayı.txt");
    while (!fin.eof()){
        string word;
        int n;
        fin >> word;  //First i read it as a string.
        if (isdigit(word[0])){ //checks whether is it an int or not
            fin.unget(); //
            fin >> n;  // if its a int read it as an int
            cout << n << endl;
        }
    }
}

假設文本文件是這樣的:

100200300 Glass
Oven 400500601

我的目的僅僅是從該文本文件中讀取整數並在控制台中顯示它們。 所以輸出應該像

100200300
400500601

您可以在上面看到我的嘗試。作為輸出,我僅得到整數的最后一位。這是示例輸出:

0
1

很簡單,只需嘗試使用字符串流將讀取的字符串轉換為int,如果失敗則不是整數,否則為整數。

 ifstream fin;
    istringstream iss;
    fin.open("Say1.txt");

    string word;
    while (fin>>word )
    {

        int n=NULL;        
        iss.str(word);

        iss>>n;

        if (!iss.fail())
        cout<<n<<endl;

        iss.clear();


    }

我認為以下應該做您想要的(未經測試的代碼):

int c;
while ((fin >> std::ws, c = fin.peek()) != EOF)
{
  if (is_digit(c))
  {
    int n;
    fin >> n;
    std::cout << n << std::endl;
  }
  else
  {
    std::string s;
    fin >> s;
  }
}

暫無
暫無

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

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