• C++ 中输入n行字符串 与 按空格字符分割


    C++ 中输入n行字符串 与 按空格字符分割

    1、背景

    输入一个正整数n,然后再输入n行字符串。

    2、实现

    基于C++具体实现代码如下,需注意的是,当输入n并敲回车,产生的换行符会继续存在于输入流缓存区中,相当于输入流里有了数据,如此则第一遍getline(cin,s) 读入的就是换行符,从而导致只能输入n-1行字符串(可自己验证),所以将输入流中的换行符去掉即可。

    针对此问题,可采用 cin 的一个方法,即 ignore(),此方法会忽略掉当前输入流中的数据;也可采用头文件 cstdio 下的 getchar(),其会读取输入流中的一个字符。

    具体代码如下:

    #include
    #include
    #include
    #include
    using namespace std;
    
    int main()
    {
    	string s;
    	vector<string> arr;
    	int n;
    	cin >> n;
    	//cin.ignore();
    	getchar();
    	while (n--)
    	{
    		getline(cin, s);
    		arr.push_back(s);
    	}
    	cout << "输入内容:" << endl;
    	for (auto& val : arr)
    	{
    		cout << val << endl;
    	}
    	return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    运行结果:
    在这里插入图片描述
    注:关于此处内容也可点击博客进行查看!

    3、一点扩展

    将包含空格的一行字符串按空格分开:

    实现代码:

    #include
    #include
    #include
    #include
    #include
    using namespace std;
    
    int main()
    {
    	string s = "hello world and how are  you!";
    	cout << "源字符串: " << s << endl << endl;
    	stringstream ss;
    	ss << s;
    	vector<string> ans;
    	string tmp;
    	while (ss >> tmp)
    		ans.push_back(tmp);
    	cout << "分割后单词:" << endl;
    	for (auto& val : ans)
    		cout << val << endl;
    	return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    运行结果:
    在这里插入图片描述
    注:此方法很简单,但会使用较多开销,因为需要将输入字符串转换为字符串流并从字符串流读取到目标字符串.

    当然也可以直接用循环遍历string类中的find()substr()去进行分割,此处就不贴对应代码了~

  • 相关阅读:
    4. 工业大数据支撑中国制造弯道取直
    论文阅读笔记 | 三维目标检测——MV3D算法
    PADS(二)更多使用和实战总结
    重写muduo网络库开发环境和前期准备
    Tomcat 源码分析 (Tomcat的Session管理之管理持久化Session) (十三)
    简易Tomcat服务器
    微信怎么把ip地址改成域名
    linux安装python3.X
    STM8的C语言编程(14)--+PWM
    vue(12)
  • 原文地址:https://blog.csdn.net/m0_51961114/article/details/126334415