C_string 个数组,将名字和姓氏分配给 fullName(C++ 初学者)

C_string arrays, assigning first and last names to fullName (C++ Beginner)

我在我的第一个 CS class 中,但我无法编译它。我查看了我教授的笔记、讲座和示例,但我输入的内容似乎并不重要,这是一个错误。我收到 38 个错误,而且只有 25 行代码!很多错误没有任何意义,例如 "expected a ;" 即使已经有一个 ';',或者 "expected a {" 在 main 之后即使它显然在那里。据我所知,visual studio 至少应该编译我的代码。非常感谢任何帮助!

一步一步Instructions/Correct输出:

编写一个产生以下输出的程序:

/* 输出

输入您的年龄:21

输入姓氏:李

你好汤姆·李。你今年21岁。

按任意键*/

1.) 声明一个名为:firstName

的数组

2.) 声明一个名为:lastName

的数组

3.) 声明一个名为:fullName

的数组

4.) 在 main() 中:

5.) 调用名为:displayInfo() 的函数。

我的代码:

#include <iostream>
#include <string>
using namespace std;

void displayInfo(char fullName, int age)

int main
{
    char firstName[10] = "Bob";
    char lastName[10] = { 0 };
    char fullName[20] = { 0 };
    int age;
    cout << "Enter your age:  ";
    cin >> age;
    cout << "\nEnter the last name:  ";
    cin.getline(lastName, 10);

    displayInfo(fullName, age)

    strcpy_s(fullName, firstName);
    strcat_s(fullName, " ");
    strcat_s(fullName, lastName);
    strcat_s(fullName, ".");

    return 0;
}
displayInfo(char fullName, int age)
{
    cout << "Hello " << fullName << "You are " << age << "years old.";
}

您的代码有一些错误,这里有一些更正(在评论中):

#include <iostream>
#include <fstream>
#include <cstring> // include this for strcpy() and strcat()

using namespace std;

// You need to have char* fullname as you are passing a cstring not a character
void displayInfo(char* fullName, int age); // You forgot the semi colon here

int main(void) // You need to have input parameters to main() it can be void
{
    char firstName[10] = "Bob";
    char lastName[10] = "0"; // Not an error but you should initialize like this
    char fullName[20] = "0"; // same here
    int age;
    cout << "Enter your age:  ";
    cin >> age;
    cout << "\nEnter the last name:  ";
    cin.getline(lastName, 10);

    strcpy(fullName, firstName); // Just use strcpy
    strcat(fullName, " "); // Just use strcat
    strcat(fullName, lastName); // Just use strcat
    strcat(fullName, "."); // Just use strcat

    // Move the display after you do string manipulation
    displayInfo(fullName, age); // You forgot semi colon here

    return 0;
}

// You need to have char* fullname as you are passing a cstring not a character
void displayInfo(char* fullName, int age) // You forgot the return type of this function
{
    cout << "Hello " << fullName << "You are " << age << "years old.";
}