字符串的输入输出
char s[maxSize];
gets(s);
scanf("%s",s);
#include <iostream>
using namespace std;
int main()
{
char s[10];
for(int i = 0; i <= 9; i++)
s[i] = "\0";
gets(s);
for(int i = 0; i <= 6; i++)
cout << i << ":" << (int)s[i] << endl;
return 0;
}
gets不接受回车符,并且在每次输入的字符串后末尾自动补上"\0"
#include <iostream>
using namespace std;
int main()
{
char s[10];
for(int i = 0; i <= 9; i++)
s[i] = "\0";
scanf("%s",s);
for(int i = 0; i <= 6; i++)
cout << i << ":" << (int)s[i] << endl;
return 0;
}
scanf以空格为当前串的输入结束标志
#include <iostream>
using namespace std;
int main()
{
char s1[10],s2[10];
for(int i = 0; i <= 9; i++)
{
s1[i] = "\0";
s2[i] = "\0";
}
scanf("%s%s",s1,s2);
for(int i = 0; i <= 6; i++)
cout << i << ":" << (int)s1[i] << endl;
cout << endl;
for(int i = 0; i <= 6; i++)
cout << i << ":" << (int)s2[i] << endl;
return 0;
}
scanf不把空格、回车、制表符当做普通字符,因为要把它们当做定界符
#include <iostream>
using namespace std;
int main()
{
char s[10];
for(int i = 0; i <= 9; i++)
s[i] = "\0";
cin >> s;
for(int i = 0; i <= 6; i++)
cout << i << ":" << (int)s[i] << endl;
return 0;
}
cin也是以空格、回车、制表符当做结束标记
#include <iostream>
using namespace std;
int main()
{
string s;
getline(cin,s);
for(int i = 0; i < s.length(); i++)
cout << i << ":" << (int)s[i] << endl;
}
总结:
gets、scanf、cin 会自动在串尾补上一个"\0"字符作为字符串的结束标记
用puts(s)、printf("%s",s)、cout >> s 可以输出s串,事实上,这三个函数都是输出从第一个字符到"\0"之前的所有字符,并且puts会自动换行