从特定文本文件中检索所有数字

时间:2015-09-30 22:02:15

标签: c++

我有以下程序:

#include <iostream>
#include <fstream>
#include <cstdlib>

using namespace std;

void tellen ()
{
    ifstream input;
    ofstream output;
    char kar;
    input.open ("test",ios::in);
    kar = input.get();
    while ( !input.eof() ){
        if ( kar >= '0' and kar <= '9'){
            cout << kar;
            kar = input.get();
        }
        else
            kar = input.get();

    }
    //cout << "Aantal characters:" << aantalchar << endl;
    //cout << "Aantal regels:" << aantalregels << endl;
}

int main()
{
    tellen();
    return 0;
} //main

我打算让这个程序做的是在命令窗口中显示某个文本文件中的所有数字(在本例中为“Test”)。我想知道为什么这不起作用?我有一个名为test的文件但是当我运行它时,命令提示符给我一个空白。当我将“test”更改为“test.txt”时,问题仍然存在。有没有人知道问题是什么?也许它与文件的位置有关?

2 个答案:

答案 0 :(得分:0)

要改变的事情:

  1. 添加一项检查以确保文件已成功打开。

  2. 使用int代替istream::get()读取字符时使用char类型。

  3. 稍微更改while语句。

  4. void tellen (){
        ifstream input;
        ofstream output;
    
        input.open ("test",ios::in);
        if ( !input )
        {
           std::cerr << "Unable to open file.\n";
           return;
        }
    
        int kar; // Don't use char.
        while ( (kar = input.get()) != EOF  ){
            if ( kar >= '0' and kar <= '9'){
               cout.put(kar); // I prefer this.
               // cout << (char)kar;
            }
        }
        //cout << "Aantal characters:" << aantalchar << endl;
        //cout << "Aantal regels:" << aantalregels << endl;
    }
    

答案 1 :(得分:0)

以下代码将为您提供名为test的txt文件的输出。

#include <iostream>
#include <fstream>
#include <cstdlib>

using namespace std;

void tellen() {
    ifstream input;
    ofstream output;

    int kar;
    char charKar;
    input.open("test.txt", ios::in);

    // could replace "test.txt" with a variable such as filePath = "/downloads/test.txt"

    if (input.is_open()) {
        while (!input.eof()) {

            kar = input.get(); //kar gets inputed as an ASCII
            charKar = static_cast<char>(kar);//charKar converts the ASCII into a char variable



            if (charKar >= '0' && charKar <= '9'){ //Evaluate charKar, not kar

                 cout << charKar << endl;

            }



        }

        input.close();
    }
    else {
        cout << "\nFile Did Not Open!";
    }


}

int main() {

    tellen();

    return 0;
} //main

我已经测试了代码并且它有效!对不起,如果它很乱我在编码时就是在做蛋,所以如果你有任何问题请问!

相关问题