从某个文本文件中检索所有数字

Retrieving all numbers from a certain text file

本文关键字:检索 数字 文件 文本      更新时间:2023-10-16

我有以下程序:

#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"时,问题仍然存在。有人知道是什么问题吗?也许这和文件的位置有关?

下面的代码将给出一个名为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

我已经测试了代码,它的工作!抱歉,如果它是混乱的,我正在制作鸡蛋,而编码这个,所以如果你有任何问题,请问!

需要改变的地方:

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

  2. 使用istream::get()而不是char读取字符时使用int类型

  3. 稍微改变一下while语句

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;
}