美文网首页
Chapter4: 字符串处理

Chapter4: 字符串处理

作者: 希崽家的小哲 | 来源:发表于2015-05-21 10:05 被阅读29次

字符串输入


#include<iostream>
using namespace std;
int main()
{
    const int size = 12;
    char name[size] ;
    char addr[size] ;
    cout<<"enter your name:\n";
    cin>>name;
    cout<<"enter your address:\n";
    cin>>addr;
    cout<<"my name is "<<name<<" live in "<<addr<<endl;
    return 0;
}

enter your name:
hey lodon aaa
enter your address:
my name is hey live in lodon

可以看出 cin 只读取单词,遇到空白(空格、制表符、换行符)结束。

每次读取一行

getline()和get()都读取一行,直到遇到换行符。getline丢弃换行符,get将换行符留在序列中。

#include<iostream>

using namespace std;
int main()
{
    const int size = 12;
    char name[size] ;
    char addr[size] ;
    cout<<"enter your name:\n";
    cin>>name;
    cout<<"enter your address:\n";
    cin.getline(addr, size);
    cout<<"my name is "<<name<<" live in "<<addr<<endl;
    return 0;
}```
>enter your name:
hello
enter your address:
my name is hello live in 

因为cin>>name 吸收了一个换行符,getline 遇到这个换行符直接跳过了。要能正常执行只需要在cin>>name 后面添加一句 cin.get() 或者 改成(cin>>name).get() 

### C++中的string 类
C++98标准通过添加string类扩展了C++库。可以用string类代替上面的字符数组来处理字符串。

相关文章

网友评论

      本文标题:Chapter4: 字符串处理

      本文链接:https://www.haomeiwen.com/subject/byilqttx.html