C ++从文件中读取并知道stream是字符串还是数字

时间:2014-05-14 17:58:15

标签: c++ ifstream

我有这样的文件

A 2 3 4 6
B 10 1 2 6

当我读它时,我需要检查我是否读过一个字符或一个数字。但我不知道怎么......

    string fileName = "/Users/Fry/Desktop/file/file/file.txt";
    ifstream myReadFile;
    myReadFile.open(fileName);
    char output[1000];

    if (myReadFile.is_open())
    {
        while (!myReadFile.eof())
        {
            myReadFile >> output;
            cout << output << endl;
        }
    }

4 个答案:

答案 0 :(得分:2)

您可以按字符串解析文件字符串,并检查每个小字符串是否为数字。类似的东西:

#include <fstream>
#include <cctype>
#include <sstream>
...
std::string tmp;
while (myReadFile >> tmp){
    // you got a string...
    if (is_number(tmp)){
        // it's a number
    }
    else{
        // it's not a number 
    }
}

要检查字符串是否为数字,您可以使用以下函数,该函数可以处理多个字符编号(如10)或非数字(如123abc45

bool is_number(const std::string& s){
    return !s.empty() && s.find_first_not_of("0123456789") == std::string::npos;
}

答案 1 :(得分:1)

包括<cctype>并使用isdigit()isalpha()查看已读取的字符。

答案 2 :(得分:1)

您可以使用标头std::isdigit中声明的标准C函数<cctype>来检查读取字符串的第一个字符(或每个字符)是否为数字,如果是,则应用C ++函数{{ 1}}

例如

std::stoi

答案 3 :(得分:0)

我不确定在这种情况下它是否相关;它看起来像我 你有一个非常固定的格式,并且可以确切地知道你是否 应该期待一封信或一个数字。但除此之外,你可以 总是偷看:

myFile >> std::skipws;      //  Since we're going to use unformatted input
if ( std::isalpha( myFile.peek() ) ) {
    //  It's a letter, extract it into a char or a string
} else {
    //  It's (hopefully) a number, extract it into an int
}

std::istream::peek 提取字符,所以它是 仍然存在正常格式化的提取器。它回来了 函数的正确范围内的int(不是char) 在<cctype>,所以你不必担心未定义 使用char调用它们时产生的行为。

此外,在检查之前,您不应该使用>>的结果 看到它成功了,你不应该使用eof() 循环的条件。