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

字符变量与字符串

dengdaidw 发布于 2013-10-23 14:33, 385 次点击
char ch;
cin>>ch;//为什么我输入字符串不会报错啊
6 回复
#2
xufan2013-10-23 14:49
那你输出的结果看了吗?
#3
dengdaidw2013-10-23 15:24
回复 2楼 xufan
我知道输出结果只输出第一个,帮忙看看这个程序啊,
#include<iostream>
using namespace std;
int main()
{
    char ch;
    int count=0;
    cout<<"enter the characters,enter '#'to quit"<<endl;
    cin.get(ch);
    while(ch!='#')
    {
        cout<<ch;
        count++;
        cin.get(ch);
    }
    cout<<endl<<count<<endl;
    return 0;
}
程序目的是计算输入的字符的个数,如果我直接输入一个字符串,与分开输入字符变量的结果不一样,为什么啊,
#4
xufan2013-10-23 16:48
如果换作是我的话,我会这样写:
程序代码:
#include <iostream>
#include <string>
int main()
{
    std::string strPtr ;
    std::cout<<"Enter the string : ";
    getline(std::cin,strPtr);
    std::cout<<(int)strPtr.size()<<std::endl;
    return 0;
}

#5
TonyDeng2013-10-23 23:02
爲什麽要報錯呢?
#6
a5929631442013-10-24 21:16
以下是引用dengdaidw在2013-10-23 15:24:19的发言:

我知道输出结果只输出第一个,帮忙看看这个程序啊,
#include<iostream>
using namespace std;
int main()
{
    char ch;
    int count=0;
    cout<<"enter the characters,enter '#'to quit"<<endl;
    cin.get(ch);
    while(ch!='#')
    {
        cout<<ch;
        count++;
        cin.get(ch);
    }
    cout<<endl<<count<<endl;
    return 0;
}
程序目的是计算输入的字符的个数,如果我直接输入一个字符串,与分开输入字符变量的结果不一样,为什么啊,

因为 空格 也是字符 要算到个数里
#7
a5929631442013-10-24 21:17
楼主 开始问的问题  为什么可以输入字符串?
因为 程序里的 while 语句  循环输入 ch  所以 可以输入字符串
1