Leg*_*Joe -2 c++ compiler-errors
我用c ++编写代码,非常简单.
using namespace std;
int main(){
char cName[30], cFirst[15], cSur[30];
cout << "Enter your name: " << endl;
cin.getline(cName, 29);
for( int i = 0; i < 29; i++)
if(cName[i] == ' ')
break;
strncpy(cFirst, cName, i);
cFirst[i] = '\0';
strncpy(cSur,cName + i + 1);
cSur[i] = '\0';
cout << cSur << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但是,程序停止编译,strncpy(cFirst, cName, i);我收到此错误消息"函数'char*strncpy(char*,const char*,size_t)'的参数太少.有人可以解释一下我做错了什么吗?
strncpy() 接受三个参数,在第二个调用中只提供两个:
strncpy(cSur,cName + i + 1);
Run Code Online (Sandbox Code Playgroud)
由于这是C++,请考虑使用std::string而不是char[](或char*).有一个版本std::getline()需要一个std::string参数并填充它,不再需要固定长度的数组.然后,您可以使用std::string::find()和std::string::substr()将行拆分为名字和姓氏:
std::string full_name("john prog rammer");
const size_t first_space_idx = full_name.find(' ');
if (std::string::npos != first_space_idx)
{
const std::string first_name(full_name.substr(0, first_space_idx));
const std::string surname(full_name.substr(first_space_idx + 1));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2911 次 |
| 最近记录: |