C++ 从文件中读取并忽略空格和 t
C++ Read from a file and ignore both whitespace and
当我有这样的文件时:
1 Boston and Chicago
或
1 Boston and Chicago
我拥有的代码:
std::string line
std::string name
int num;
getline(filename, line);
在这两种情况下,如何将数字 1 存储在 num 变量中,将"Boston and Chicago"字符串存储在名称变量中?第一种情况只有一个空格,另一种情况有 \t 空格。
您需要标记该行。 现在,如果它总是一个数字,后跟一些空格(tab是一种空格(,然后是一个字符串,你可以做这样的事情:
std::string::size_t nloc = std::string::npos;
if(std::string::npos != (nloc = line.find_first_of(" t")))
{
std::string first = line.substr(0, nloc);
std::string second = line.substr(nloc+1, line.length() - nloc);
// perform other processing of first and second here
}
此处完整描述了函数find_first_of
。 请注意,对于上述操作,您可能需要进行额外的处理(例如删除前导或尾随空格,但对于find_first_of
和find_first_not_of
函数,这是微不足道的(。
完成此操作后,您可以使用atoi
将第一个字符串转换为整数(尽管我会进行验证以确保第一个字符串在进行转换之前仅包含数字(。
相关文章:
- 如何在 C++ 中从文件中读取字符数组(带有一些空格)
- 如何逐行读取文件,每行中的内容都用空格分隔并将其写入新文件中
- 从输入文件修剪空格
- 名称具有空格的文件未编译
- 文件读取C++包括空格键
- 忽略从文件中读取前导空格
- 从文本文件中读取所有内容,直至空格
- 使用空格分隔符从文本文件将对象读入数组
- 用空格填充 2D 数组(从文件输入)
- 如何在Boost::program_options配置文件中为非字符串的自定义选项值类型处理空格
- 如何在.pro文件中为TARGET使用空格和尖括号
- 如何从文件中读取用空格分隔的数字
- C++ 逐行从文件(包含空格)读取数据
- 如何在 c++ 中将文件中的无空格插入器读取到数组中?
- 从文本文件中读取数据并删除所有换行符空格,并在 C++ 控制台中显示
- 从文件中读取多行.txt字符串删除空格并创建新文件进行输出
- 如何读取文件忽略第一个空格?
- C++ : 如何在使用 getline() 和 ifstream 对象从文件中读取一行时跳过第一个空格?
- 无法显示带有保存在文件中的空格的名称
- 使用 fstream 在空格分隔文件中查看下一项(不仅仅是一个字符)的方法