-3

我正在用 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;
}

但是,程序停止编译strncpy(cFirst, cName, i);并且我收到此错误消息 'too few arguments to function 'char* strncpy(char*, const char*, size_t)' 。有人可以解释我做错了什么吗?

4

3 回答 3

8

strncpy()接受三个参数,在第二个调用中只提供两个:

strncpy(cSur,cName + i + 1);

由于这是 C++,请考虑使用std::string代替char[](或char*)。有一个版本std::getline()将 astd::string作为参数并填充它,从而不再需要固定长度的数组。然后,您可以使用std::string::find()andstd::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));
}
于 2012-05-29T10:56:13.623 回答
4

如果你问我,这很清楚地意味着你只提供了 2 个参数而不是 3 个:

strncpy(cSur,cName + i + 1);
于 2012-05-29T10:56:18.077 回答
2

它抱怨它接受了 3 个参数,但你没有提供 3 个参数。

会是这条线:

strncpy(cSur,cName + i + 1);

在这里,您只提供 2,因为您将 i 和 1 添加到 cName

于 2012-05-29T10:57:27.597 回答