gpt4 book ai didi

C++ : Turn char array into a string that is printed

转载 作者:行者123 更新时间:2023-11-28 06:45:40 25 4
gpt4 key购买 nike

只是一个学习基础 C++ 的初学者。我正在尝试找出最佳方法:

  1. 将Name为20的char数组转成可以打印的字符串。我在其他 Stack Overflow 主题中发现使用“str()”,例如“str(Name)”,但它总是出现“找不到标识符”。

    cout << "Name:" << str(Name) << endl;
  2. 设置一个 20 个字符的 char 数组。出于某种原因,以下在声明时给我错误。我已经调整了很多次,但我不明白为什么它不给。

    TESCStudent.Name[20] = {'S','u','p','e','r','P','r','o','g','r','a','m','m','e','r','\0'};

我目前的完整代码:

#include <iostream>
#include <conio.h>
#include <string>
using namespace std;

//Step 1
struct StudentRecord
{
char Name[20];
//Accessor
void printInfo() const;
};

void StudentRecord::printInfo() const
{
cout << "Name:" << str(Name) << endl;
}

int main()
{
//Step 2
StudentRecord TESCStudent;
TESCStudent.Name[20] = {'S','u','p','e','r','P','r','o','g','r','a','m','m','e','r','\0'};

//Step 3
TESCStudent.printInfo();

_getch();
return 0;
}

最佳答案

鉴于您处于非常初级的水平,只需使用 std::string:

#include <iostream>
#include <conio.h>
#include <string>

struct StudentRecord {
std::string Name;
void printInfo() const {
std::cout << "Name:" << Name << '\n';
}
};

int main() {
StudentRecord TESCStudent;
TESCStudent.Name = "SuperProgrammer";
TESCStudent.printInfo();

_getch();
}

Live demo

关于C++ : Turn char array into a string that is printed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25042320/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com