C++字符串输入有关问题(就几行代码),多谢大家帮忙
C++字符串输入问题(就几行代码),谢谢大家帮忙
#include <iostream>
#include <string>
using namespace std;
void main()
{
1 string ch;
2 getline(cin,ch);//在用这个输入字符串时候,为什么需要点击两次回车键才算输入字符串完毕?(删掉第四行才能运行)
3 cout<<ch<<endl;
4 cout<<"length is "<<strlen(ch)<<endl;//为什么添加了strlen这行代码后,成粗就报错了?那应该怎样计算字符串大小?
}
谢谢大家帮忙
------解决方案--------------------
string不能用strlen来计算长度,要用成员函数.size();
另外我没有碰到两次回车才OK的情况,我一次就行了
#include <iostream>
#include <string>
using namespace std;
void main()
{
1 string ch;
2 getline(cin,ch);//在用这个输入字符串时候,为什么需要点击两次回车键才算输入字符串完毕?(删掉第四行才能运行)
3 cout<<ch<<endl;
4 cout<<"length is "<<strlen(ch)<<endl;//为什么添加了strlen这行代码后,成粗就报错了?那应该怎样计算字符串大小?
}
谢谢大家帮忙
------解决方案--------------------
string不能用strlen来计算长度,要用成员函数.size();
另外我没有碰到两次回车才OK的情况,我一次就行了
- C/C++ code
#include <iostream> #include <string> #include <cstring> using namespace std; int main() { string ch; getline(cin,ch);//在用这个输入字符串时候,为什么需要点击两次回车键才算输入字符串完毕?(删掉第四行才能运行) cout<<ch<<endl; cout<<"length is "<<ch.size()<<endl;//为什么添加了strlen这行代码后,成粗就报错了?那应该怎样计算字符串大小? }
------解决方案--------------------
string对象不能用strlen计算长度
要用对象的方法size()取得长度
输入2次回车的问题,也许是vc6.0的问题
------解决方案--------------------
strlen()
需要一个const char*类型参数而你的ch是string类型肯定出错
char ch[]="hello world";
strlen(ch);
strlenf返回11