服务器之家

服务器之家 > 正文

C++实现从输入中读取字符串

时间:2021-04-04 15:16     来源/作者:C++教程网

你可以用这种方式读取一个单独的以空格结束的词:

?
1
2
3
4
5
6
7
8
9
#include<iostream>
#include<string>
using namespace std;
int main(){
  cout << "Please enter a word:\n";
  string s;
  cin>>s;
  cout << "You entered " << s << '\n';
}

注意,这里没有显式的内存管理,也没有可能导致溢出的固定大小的缓冲区。

如果你确实想得到一行而不是一个单独的词,可以这样做:

?
1
2
3
4
5
6
7
8
9
#include<iostream>
#include<string>
using namespace std;
int main(){
  cout << "Please enter a line:\n";
  string s;
  getline(cin,s);
  cout << "You entered " << s << '\n';
}
标签:

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
Intellij idea2020永久破解,亲测可用!!!
Intellij idea2020永久破解,亲测可用!!! 2020-07-29
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
返回顶部