C++实现读取输入流

C++实现读取输入流

C++ string默认的输入流:

不读取头尾的空格,若中间有空格则进行换行处理。

C++的getline函数:

读取所有空格,但无法识别换行符。

源代码

1.C++string默认的输入流:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/*************************************************************************
    > File Name: 3.2.2.1.1.cpp
    > Author: puruidong
    > Mail: 1@w1520.com
    > Created Time: 2013年12月12日 星期四 16时55分17秒
 ************************************************************************/

#include<iostream>
#include<string>
using namespace std;
using std::cin;
using std::string;
using std::cout;
using std::endl;

int main()
{
    string word;
    while(cin >> word){
        cout << word << endl;
    }
    return 0;
}

2.getline函数读取输入流

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/*************************************************************************
    > File Name: 3.2.2.1.2.cpp
    > Author: puruidong
    > Mail: 1@w1520.com
    > Created Time: 2013年12月12日 星期四 17时02分44秒
 ************************************************************************/

#include<iostream>
#include<string>
using namespace std;
using std::string;
using std::cin;
using std::cout;
using std::endl;

int main()
{
    string line;
    // read line at time until end-of-file
    while(getline(cin,line)){
        cout << line << endl;
    }
    return 0 ;
}

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

*

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据