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

时间:2014-12-08 17:40:42

标签: c++

当我有这样的文件时:

1 Boston and Chicago 

OR

1   Boston and Chicago 

我的代码:

std::string line 
std::string name 
int num; 
getline(filename, line);

如果在num变量中存储数字1,在两种情况下如何将“Boston and Chicago”字符串存储在name变量中?第一种情况只有一个空格,另一种情况只有一个空格。

1 个答案:

答案 0 :(得分:0)

您需要对该行进行标记。现在,如果它总是一个数字,然后是一些空格(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
     }

full here中描述了函数find_first_of。请注意,对于上述内容,您可能需要执行其他处理(例如删除前导或尾随空格,但使用find_first_offind_first_not_of函数这是微不足道的。)

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