C++检查从文件中读取的最后内容是否是数字
C++ check if the last thing read from file was a number
这是一个
相当原始的问题,所以我想解决方案应该不难,但我没有找到一种方法可以简单地做到这一点,也没有总结它以实际在互联网上找到它。
所以进入问题,我有一个这样的信息文件:
1988 Godfather 3 33 42
1991 Dance with Wolves 3 35 43
1992 Silence of the lambs 3 33 44
我要求将所有信息放在一个数据结构中,所以假设它将是int year
、string 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];
恕我直言,将文件中的分隔符从空格更改为其他字符,例如 ; 或 : ,将大大简化解析。例如,如果以后数据规格发生变化,而不是只有最后三个,最后三个或最后四个可以是整数,那么上面的代码将需要重大重构。
相关文章:
- C++LDAP检查用户是否是特定组的成员
- 检查某些类型是否是模板类 std::optional 的实例化
- 将错误返回给调用方而不是立即在 C++ 中抛出错误是否是一种好的做法
- 如何检查模板专用化是否是基本模板的子类?
- 如何检查变量是否是C++中的地图?
- C++ Chrono 确定一天是否是周末?
- 将相同共享指针的副本存储在不同的向量中是否是一种好的做法?
- 使用类在C++中存储和列出变量/方法是否是一种好的做法
- 代码在 CodeSignal 中工作不正确。不确定这是否是我的代码缺陷
- 如果 C 函数仍然可以间接执行(通过回调函数),那么将它声明为静态函数是否是一种不好的做法?
- MFC 中的窗口消息管理:添加基类调用是否是强制性的?
- 检查 n2 是否是 n1 的倍数后结果错误,但根本没有错误
- C ++:检查它是否是类中的数字
- 如何检查字符串中的最后一个字符是否是某个字符并将其从字符串中删除?(C++)
- 如何确定输入文件中的一行是否是最后一行?C++
- C++检查从文件中读取的最后内容是否是数字
- 检查当前元素是否是集合的最后一个元素
- 如何使用 for(int i:myVector) 代码样式知道元素是否是矢量中的最后一个元素
- 检测迭代器是否是std::map的最后一个元素
- 在c++中,如何确定一个类是否是继承链中的最后一个类/子类?它位于基类的另一端