2017-10-17 148 views
0

我有这样的代码:省略换行符在读取文件与C++

#include <iostream> 
#include <string> 
#include <fstream> 

int main() 
{ 
    std::ifstream path("test"); 
    std::string separator(" "); 
    std::string line; 
    while (getline(path, line, *separator.c_str())) { 
     if (!line.empty() && *line.c_str() != '\n') { 
      std::cout << line << std::endl; 
     } 

     line.clear(); 
    } 

    return 0; 
} 

文件“测试”被填充有数字,通过各种数目的空格分隔。我只需要阅读数字,一个接一个,省略空格和换行符。此代码省略了空格,但不包含换行符。

这些都是从输入文件“测试”几行字:

 3  19  68  29  29  54  83  53 
    14  53  134  124  66  61  133  49 
    96  188  243  133  46  -81  -156  -85 

我认为问题是,这*line.c_str() != '\n'不是确定字串line命中换行符和程序保留打印的正确方法换行符!

这一个伟大的工程:

#include <iostream> 
#include <string> 
#include <fstream> 

int main() 
{ 
    std::ifstream path("test"); 
    std::string separator(" "); 
    std::string line; 
    while (getline(path, line, *separator.c_str())) { 
     std::string number; 
     path >> number; 
     std::cout << number << std::endl; 
    } 

    return 0; 
} 
+0

而不是'* line.c_str()=“\ n''你应该检查该行不仅包含空格。很难说,没有看到输入的例子(请把它做出来,这样我们可以看到'\ n''字符在哪里)。 – user0042

+1

你只是检查第一个字符是换行符。如果一个数字在行的末尾,换行符将是'line'的最后一个字符,而不是第一个字符。 – Barmar

+2

为什么不使用'path >> number;',它将跳过任何空格并读取一个数字。 – Barmar

回答

1

使用流运算符>>阅读整数:

std::ifstream path("test"); 
int number; 
while(path >> number) 
    std::cout << number << ", "; 
std::cout << "END\n"; 
return 0; 

这将列出所有的整数中的文件,假设他们用空格隔开。

getline的正确用法是getline(path, line)getline(path, line, ' ')其中最后一个参数可以是任何字符。

*separator.c_str()在这种情况下转换为' '。不建议使用此用法。

同样*line.c_str()指向line中的第一个字符。为了找到最后一个字符用

if (line.size()) 
    cout << line[size()-1] << "\n"; 

当使用getline(path, line)line将不包括最后\n字符。

这是getline的另一个例子。我们读取该文件逐行,然后每行转换为stringstream,然后从每行读取整数:

#include <iostream> 
#include <string> 
#include <fstream> 
#include <sstream> 

int main() 
{ 
    std::ifstream path("test"); 
    std::string line; 
    while(getline(path, line)) 
    { 
     std::stringstream ss(line); 
     int number; 
     while(ss >> number) 
      std::cout << number << ", "; 
     std::cout << "End of line\n"; 
    } 
    std::cout << "\n"; 
    return 0; 
} 
1

使用内置到C++的isdigit功能。

+0

此功能是否考虑到符号? – Pekov

+0

不,但你可以随时进行测试,isdigit只会过滤非数字号码。 – Lavevel