龙羽 发表于 2013-11-8 23:50:16

求助大神啊 在线等


最后一行输出的line的值为什么为空?

friendan 发表于 2013-11-8 23:50:17

看我的代码注释(望楼主以后发帖,学会帖代码呀,看截图写代码很浪费时间答题的):#include "stdafx.h"
#include<iostream>
#include<vector>
#include<string>
#include<sstream>
#include<cctype>

using namespace std;
int main()
{
        string line;
        string line2="abc";
        getline(cin,line);//将用户输入的字符串放到line中
        istringstream hhh(line);//创建istringstream对象hhh
        while(hhh>>line)//从hhh中以空格为界提取字符串放到line中,循环结束时line的值为空
        {
                cout<<line2<<endl;
                cout<<line.c_str()<<endl;
        }

        cout<<"跳出循环了!"<<endl;
        cout<<line<<endl;//如果line的值不为空,怎么可能跳出上面的while循环呢?

        return 0;
}



friendan 发表于 2013-11-9 13:36:22

我给你一个改进的例子代码吧:#include "stdafx.h"
#include<iostream>
#include<vector>
#include<string>
#include<sstream>
#include<cctype>

using namespace std;
int main()
{
      //istringstream对象可以绑定一行字符串,
      //然后以空格为分隔符把该行分隔开来
      string line="11 22 33 44 55";
      string s;
      istringstream hhh(line);
      while(hhh>>s)
      {
                cout<<s.c_str()<<endl;
      }
      cout<<"循环结束了!"<<endl;
      cout<<line;
      return 0;
}

效果截图:


页: [1]
查看完整版本: 求助大神啊 在线等