C++检查从文件中读取的最后内容是否是数字

C++ check if the last thing read from file was a number

本文关键字:最后 是否是 数字 读取 检查 文件 C++      更新时间:2023-10-16
这是一个

相当原始的问题,所以我想解决方案应该不难,但我没有找到一种方法可以简单地做到这一点,也没有总结它以实际在互联网上找到它。
所以进入问题,我有一个这样的信息文件:

1988 Godfather 3 33 42
1991 Dance with Wolves 3 35 43
1992 Silence of the lambs 3 33 44

我要求将所有信息放在一个数据结构中,所以假设它将是int yearstring name和另外三种int类型的数字。但是我怎么知道我读的下一件事是否是一个数字呢?我永远不知道这个词有多长。
提前感谢您为这样一个原始问题花时间的人。 :)
编辑:不要考虑标题中有数字的电影。

当你尝试解析其他电影时,你会遇到一些主要问题,比如《自由威利2》。

您可以尝试将其视为 std::stringstream,并依靠最后三个块作为您要查找的数据,而不是使用正则表达式进行泛化。

最好的选择是使用正则表达式C++

这将使您对要解析的内容进行更精细的控制。例子:

year -> d{4}
word -> w+
number->d+

如果您无法控制文件格式,则可能需要执行以下操作(伪进程):

1) read in the line from the file
2) reverse the order of the "words" in the file
3) read in the 3 ints first
4) read in the rest of the stream as a string
4) reverse the "words" in the new string
5) read in the year
6) the remainder will be the movie title

将每个字段作为字符串读取,然后将相应的字符串转换为整数。

1)initially 
  1983 
  GodFather
  3
  33
  45 
  are all strings and stored in a vector of strings (vector<string>).
2)Then 1983(1st string is converted to integer using atoi) and last three strings are also converted to integers. Rest of the strings constitute the movie_name

以下代码是在假设输入文件已针对格式进行验证的情况下编写的。

// open the input file for reading
ifstream ifile(argv[1]);
string input_str;
//Read each line        
while(getline(ifile,input_str)) {
stringstream sstr(input_str);
vector<string> strs;
string str;
while(sstr>>str)
    strs.push_back(str);
    //use the vector of strings to initialize the variables
    // year, movie name and last three integers
            unsigned int num_of_strs = strs.size();
            //first string is year
    int year = atoi(strs[0].c_str());
            //last three strings are numbers
    int one_num = atoi(strs[num_of_strs-3].c_str());
    int two_num = atoi(strs[num_of_strs-2].c_str());
    int three_num = atoi(strs[num_of_strs-1].c_str());
    //rest correspond to movie name
    string movie_name("");
    //append the strings to form the movie_name
            for(unsigned int i=1;i<num_of_strs-4;i++)
        movie_name+=(strs[i]+string(" "));
        movie_name+=strs[i];

恕我直言,将文件中的分隔符从空格更改为其他字符,例如 ; 或 : ,将大大简化解析。例如,如果以后数据规格发生变化,而不是只有最后三个,最后三个或最后四个可以是整数,那么上面的代码将需要重大重构。