Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
282 views
in Technique[技术] by (71.8m points)

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

just a beginner student learning basic C++. I'm trying to figure out the best way to:

  1. Turn a char array Name of 20 into a string that can be printed. I found in other Stack Overflow topics to use "str()" such as "str(Name)", but it always comes up 'identifier not found'.

    cout << "Name:" << str(Name) << endl;
    
  2. Set a char array of 20 characters. For some reason, the following gives me errors when declaring. I've tweaked it so many times, but I cannot get why it won't give.

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

Full code I have so far:

#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',''};

//Step 3
TESCStudent.printInfo();

_getch();
return 0;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Given that you are at a very beginner level, just use std::string:

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

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

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

    _getch();
}

Live demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...