C++ 从文件中读取并忽略空格和 t

C++ Read from a file and ignore both whitespace and

本文关键字:空格 文件 读取 C++      更新时间:2023-10-16

当我有这样的文件时:

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_offind_first_not_of函数,这是微不足道的(。

完成此操作后,您可以使用atoi将第一个字符串转换为整数(尽管我会进行验证以确保第一个字符串在进行转换之前仅包含数字(。