gpt4 book ai didi

C++ 字符数组不工作

转载 作者:行者123 更新时间:2023-11-30 02:18:50 25 4
gpt4 key购买 nike

我试图让这个程序运行,但得到奇怪的输出。我知道 char 缓冲区在这里并不理想,但它是用于分配而不是我自己设计的。这是我的代码:

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


//Place your class definition here
class student {
public:
void inputData(int a, char s[20], float e, float m, float sci);
void printData();

private:
int admno;
char sname[20];
float eng;
float math;
float science;
float total;
float ctotal();
};


int main () //This is your main driver. Do NOT make any changes to it
{
student obj ;
int a;
char s[20];
float e, m, sci;
cin >> a;
cin.getline(s,20);
cin.clear();
cin.ignore(10,'\n');
cin >> e;
cin >> m;
cin >> sci;
obj.inputData(a, s, e, m, sci);
obj.printData();
return 0;
}

//Place your class member function definitions here

void student::inputData(int a, char s[], float e, float m, float sci) {
admno = a;
*sname = *s;
eng = e;
math = m;
science = sci;
total = ctotal();
}

void student::printData() {
cout << "Admission number: " << admno << endl << "Student name: ";
for (int i = 0; i < 20; i++)
cout << sname[i];
cout << endl << "English: " << eng << endl << "Math: " << science << endl << "Science: " << science << endl << "Total: " << total;
}

float student::ctotal() {
return (eng + math + science);
}

这是我的输入:

98745
Kyle Smith
98
78
62

这是预期的输出:

Admission number: 98745
Student name: Kyle Smith
English: 98
Math: 78
Science: 62
Total: 238

这是实际的输出:

Admission number: 98745
Student name:  m ╩`uÄM■Å■   ║k`u
English: 98
Math: 62
Science: 62
Total: 238

请指教如何修复。我必须坚持使用那个字符缓冲区,但不知道为什么会出现这种损坏。谢谢!

最佳答案

*sname = *s;

这会复制一个字符,而不是整个字符串。如果要复制整个字符串,需要使用std::strcpy

std::strcpy(sname, s);

或循环

char* src = s;
char* dst = sname;
while (src) {
*dst = *src;
++src;
++dst;
}

当然,您可以取消所有这些手动字符串处理并使用 std::string相反:

//Place your class definition here
class student {
public:
void inputData(int a, std::string s, float e, float m, float sci);
void printData();

private:
int admno;
std::string sname;
float eng;
float math;
float science;
float total;
float ctotal();
};

void student::inputData(int a, std::string s, float e, float m, float sci) {
admno = a;
sname = std::move(s);
eng = e;
math = m;
science = sci;
total = ctotal();
}

关于C++ 字符数组不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51757048/

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