使用空格分隔符从输入流拆分字符串 [英] Splitting string from inputstream with whitespace delimiter

查看:131
本文介绍了使用空格分隔符从输入流拆分字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎无法用空白分隔符拆分我的字符串。



我试图使用getline(cin,myString)。



我输入的字符串为10 20 30,当我打印到输出流的字符串,我得到20 30,但不是10。 p>

我也试过了(cin >> string)。

解决方案



/ div>

您可以使用 istringstream

  ; 
getline(cin,str);
istringstream ss(str);

for(string word; ss>> word;)
cout<<单词<< endl;



$ c> while(cin>> str); 不会停止,除非:



  1. 发生EOF(您的电子邮件地址)。>可以使用 Ctrl + Z Ctrl + D F6 系统)


  2. 用户定义的条件: if(str.find('\\\
    '))break;



I can't seem to split my string with the whitespace delimiter.

I tried using the getline(cin, myString).

I input the string as "10 20 30", when I print the string onto the output stream, I get "20 30", but not the 10.

I also tried the while(cin >> string). It works here, but the while loops never terminates.

Any help is appreciated.

解决方案

You can use istringstream:

string str;
getline(cin, str);
istringstream ss(str);

for(string word; ss >> word; )
    cout << word << endl;

 

Your while(cin >> str); doesn't stop unless:

  1. Something fails in >> which is hard in your case.

  2. EOF occurs (You can use Ctrl+Z, Ctrl+D, F6 It depends on your system)

  3. A user defined condition: if(str.find('\n')) break;

这篇关于使用空格分隔符从输入流拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆