注册 登录
编程论坛 C++教室

一个有趣的问题。

棉雨 发布于 2011-05-09 23:56, 1037 次点击
这个程序的运行环境是vc++6.0
#include<iostream.h>
#include"string"
int main()
{     
    char str[100],*p;
    int i,count=0;
    p=str;
    cout<<"请输入一个句子:";  /*这么写,跟这么写:cout<<"\n请输入一个句子:";运行的时候,显示不出来这一句话,要是cout<<"请输入一个句子:"<<endl;跟这么写:cout<<"\n请输入一句话:"<<endl;那就可以显示。大家可以试试。  
    gets(p);   
    while(*p!='\0')   
    {        
        if(*p==' ')
        {            
            p++;            
            continue;
        }
        else
        {
            count++;
            i=0;
            while(*(p+i)!=' '&&*(p+i)!='\0')
                i++;
            p+=i;
        }   
    }   
    cout<<"这个句子有"<<count<<"个词";
    return 0;
}
13 回复
#2
yuccn2011-05-10 09:50
怎么个有趣法?我觉得无趣
#3
rjsp2011-05-10 14:49
错误很多,基础太差

这个程序的运行环境是vc++6.0 // VC++6.0连CPP98都支持不好,何况CPP2003,你就不该用VC98来写C++代码
#include<iostream.h> // C++中没有<iostream.h>,只有 <iostream>
#include"string" // C/C++标准从来没说过可以这么写,少听那些一知半解的家伙瞎扯,唯一正确写法只有 #include <string>

1. 你不该混用 C++的cout 和 C的gets
2. 如果你想混用,你得知道它们的机制,前者是带缓冲的。因此你得写成 cout<<"请输入一个句子:"<<flush;
   flush的作用自己去查;end相当于 <<'\n'<<flush;
3. tie函数用于使得两个"流"同步

#include <iostream>
#include <string>
#include <sstream>

int main()
{
    using namespace std;

    cin.tie( &cout ); // 这一句可以省略,因为缺省情况下,cin和cout是系住的。如果是其他流,类似的这一句必不可少

    cout << "Please enter a sentence:";
    string line;
    getline( cin, line );

    istringstream is( line );
    for( string word; is>>word; )
    {
        cout << word << '\n';
    }
    cout << endl;

    return 0;
}
#4
棉雨2011-05-10 15:44
回复 3楼 rjsp
只有说佩服二字了,谢谢你
#5
shiyuedef2011-05-10 22:21
C++里面写<iostream.h>没有错的把
#6
肖付2011-05-10 23:02
回复 5楼 shiyuedef
我也觉得是有的吧,可以直接用的.
#7
诸葛修勤2011-05-11 09:56
看下标准 和传统 之间的差别吧
#8
hellovfp2011-05-11 10:59
不要再用老的如<iostream.h>这样的头文件了,C++新标准里是没有.h之说。
#include <iostream>
#include <string> //字符串
#include <map>    //映射
#include <vector> //向量表
#include <stack>  //栈
#include <list>   //链表
。。。。。。。。
你如果还想用老的C库函数,可以用C前辍
#include <cstdio>//原stdio.h
#include <cmath>//原math.h
#include <cstdlib>//原stdlib.h
#9
donggegege2011-05-11 12:46
,C++新标准里是没有.h
#include <iostream>
#include <string> //字符串
#include <map>    //映射
#include <vector> //向量表
#include <stack>  //栈
#include <list>   //链表
。。。。。。。。
不过使用的时候必须加上名字空间:using namespace std;
#10
Demon_JIE2011-05-11 20:31
现在都是用的using namespace std;
#11
pangding2011-05-12 11:30
其实就是缓冲的问题。
C++ 里引入了新的机制,自然也要有新的方法。
C 里也有缓冲。不过混用二者确实不是好习惯。
#12
棉雨2011-05-14 07:39
多谢各位指教。
#13
zhaiguanjie72011-05-18 20:09
完全看不懂的  O(∩_∩)O~
#14
雨的帝国2011-05-22 16:11
这个,不了解,求高手解析
1