为什么这段代码不起作用?C++

jho*_*ars 0 c++

此代码应该询问用户他们的名字,然后将其拆分到该空间.

它应该首先在变量中加上firstname,在变量lastname中加上最后一个名字

#include <iostream>

using namespace std;

int main()
{
char string[80];
char first[20];
char lastname[20];
bool f = true;
int c = 0;
cout << "Whats your Name? \n";
gets(string);

for(int i =0; i < strlen(string); i++){
    if(string[i] == ' ') {
        f = false;
        c = 0;
    }

    if(f) {
        first[c] = string[i];
    } else if(!f) {
        lastname[c] = string[i];
    }


    c++;
}

for(int i = 0; i < strlen(first); i++) {
    cout << first[i] << "\n";
}
for(int i = 0; i < strlen(lastname); i++) {
    cout << lastname[i]<< "\n";
}

return 0;
}
Run Code Online (Sandbox Code Playgroud)

Mat*_*ton 5

除非你真的需要仅使用C函数来编写它,否则使用C++字符串会容易得多.

像(这是未经测试的):

std::string input;
std::string first;
std::string lastname;

// prompt the user
std::cout << "What's your name? ";
// get a line of input
std::getline(std::cin, input);

// find a space in the string
size_t space = input.find_first_of(" ");
// was the space found?
if (space != std::string::npos)
{
    // copy out the first and last names
    first = input.substr(0, space);
    lastname = input.substr(space + 1);

    // output them to stdout
    std::cout << first << std::endl << lastname << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

这意味着您不必担心空终止字符串或字符串长度或类似的东西.正如flolo所说,你的代码不会这样做,因此肯定会遇到问题.C字符串的内存布局是一个字符数组,末尾有一个空字节,这就像strlen()这样的东西知道字符串结尾的位置.此外,当有人输入一个超过20个字符的名字时,你的代码会有一段可怕的时间,这并不是特别难以置信.