C++;:将字符数组转换为打印的字符串 只是初学C++的初学者。我正试图找出最好的方法:
将字符数组名20转换为可以打印的字符串。 我在其他堆栈溢出主题中发现了使用“str()”的方法,例如“str(Name)”,但它总是出现“identifier not found”C++;:将字符数组转换为打印的字符串 只是初学C++的初学者。我正试图找出最好的方法:,c++,arrays,string,char,C++,Arrays,String,Char,将字符数组名20转换为可以打印的字符串。 我在其他堆栈溢出主题中发现了使用“str()”的方法,例如“str(Name)”,但它总是出现“identifier not found” cout << "Name:" << str(Name) << endl; 到目前为止,我拥有完整的代码: #include <iostream> #include <conio.h> #include <string> using name
cout << "Name:" << str(Name) << endl;
到目前为止,我拥有完整的代码:
#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;
//第一步
结构StudentRecord
{
字符名[20];
//存取器
void printInfo()常量;
};
void StudentRecord::printInfo()常量
{
鉴于您处于非常初级的水平,只需使用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();
}
#包括
#包括
#包括
结构StudentRecord{
std::字符串名;
void printInfo()常量{
std::cout语法如下:
char Name[20] = {'S','u','p','e','r','\0'};
用于在定义变量时初始化它。但是,在您的情况下
StudentRecord TESCStudent;
TESCStudent.Name[20] = ...;
您之前已经在行中定义了它,因此您不能“初始化”,您必须“分配”它
这就是为什么你使用std:string
而不是char[]
为什么你不直接使用std::cout一个char
数组已经是一个可以打印的字符串。通过执行cout来测试它。你为什么用char[]
而不是std::string
?@clcto“初学者只是学习C++的基础……”0x499 602D2更多的理由使用<代码> STD::String < /Cal>。<代码> [Cord](与 STD::String )绝对不是“基本C++”。“混淆你。我确信它是相反的意思:C++初学者倾向于过度使用字符数组,而有经验的程序员则欣赏 STD::String 的好处。@ ChristianHackl初学者和有经验的程序员(尤其是初学者)都应该使用<代码> STD::String < /代码>。是你以后可能想学的东西。C++初学者往往过度使用<代码> char 数组,因为有一些可怕的教程在那里提倡这样的东西(通常与<代码>新< /代码>和<代码>新[] <代码>过度使用)@Jeffrey:我认为他们也过度使用了它,因为他们要么来自C语言,要么来自一种新的语言,在这种语言中数组一开始并不十分危险,要么因为他们认为内置功能必须是首选。@ChristianHackl我被要求并指示使用char[]。这就是为什么我不需要它。
StudentRecord TESCStudent;
TESCStudent.Name[20] = ...;