简体   繁体   English

如何从C++中的一行读取整数?

[英]How to read integers from a line in C++?

I want to read integers in a line from a file.我想从文件中读取一行中的整数。

For example the line is : 3/2+5-5例如该行是:3/2+5-5

I think I need to use >>, but it stopped because of the characters;我想我需要使用>>,但它因为字符而停止了;

I also try to use other functions, but they are all for characters.我也尝试使用其他功能,但它们都是针对字符的。

As the @Fang already pointed out, there's no easy way to do it.正如@Fang 已经指出的那样,没有简单的方法可以做到。 You can read the whole line and tokenize it via the following code:您可以阅读整行并通过以下代码对其进行标记:

std::ifstream f("file.txt");

std::string line;
std::getline(f, line);

std::vector<std::string> integers;
boost::split(integers, line, boost::algorithm::is_any_of("+-*/"), boost::token_compress_on);

// Then convert strings from the integers container to ints

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM