gpt4 book ai didi

c++ - 将 C 字符串转换为 int 数组

转载 作者:太空宇宙 更新时间:2023-11-04 13:55:29 25 4
gpt4 key购买 nike

所以对于我的编程任务,我必须

处理来自输入文件的数据并对它做一些事情。

这是参数。

一位讲师的类(class)不超过 40 名学生,每名学生参加 6 项测试。为了类的每个学生,输入文件中都有一行。该行包含学生的第一个姓名(不超过 10 个字符)、姓氏(不超过 12 个字符)、ID#(6 个字符的字符串)和 6 个整数考试分数。输入文本文件应命名student_input.dat

还要注意之间的空格数量姓名、ID 和等级可以是任意的,即任何数字。不过至少会有一个空间。最后一年级和表示行“/n”结尾的不可见符号之间可能有一个空格。每行的字符总数不会超过 256,包括末尾线条符号。

而且我们不能使用任何涉及字符串的东西,所以这几乎限制了我只能使用 c 字符串。

我的问题是,我目前一直在尝试将提取的 char 字符串(即成绩)转换为 int 数组,以便我可以对它们进行数学运算。

这是我当前的代码。

int main()
{
char * lastName;
char * firstName;
char * idNumber;
char * testScores;
char rawData[256] = "";
ifstream fin;
ofstream fout;

fin.open("student_input.dat");

if (!fin)
{
cout << "Program terminated. Input file did not open." << endl;
fin.close();
return 1;
}

if(fin)
{
for( int i = 0; i < 41; i++)
{
fin.getline(rawData, 256, '\n');
lastName = strtok(rawData, " ");
cout << lastName;
firstName = strtok(NULL, " ");
cout << firstName;
idNumber = strtok(NULL, " ");
cout << idNumber << " ";
for( int j = 0; j < 6; j++)
{
testScores = strtok(NULL, " ");
cout << testScores << " ";
}
cout << endl;
}
}

return 0;
}

最佳答案

如果我对问题的理解正确,那么您可能遇到了两个具体问题:

  1. 如何从字符串中提取具体的数据值?
  2. 如何将包含数字字符的字符串转换为数字?

我给你两个解决方案(不发布实际代码,因为它(可能)是学校作业)。

解决方案一:

1. Let input be a string or array of characters
2. Read the entire line into input
3. Set index = 0
4. while (index is not beyond the end of input)
4.1. Set start = (first non-whitespace character in input starting from index)
4.2. Set end = (first whitespace character / end of line character / end of file in input starting from start)
4.3. Set substring = (string containing the characters in input from indices start to end-1, both end inclusive)
4.4. Save substring (into an array or whatever).
4.5. Set index = end
5. end-while

这样,您就可以将所有以空格分隔的子字符串作为不同的字符串。根据需要处理它们(即,第一个子字符串是名字,第二个是姓氏,依此类推)...

找到包含成绩的字符串后,可以使用问题评论中的 atoi 或编写一个函数,将包含单个数字的字符串转换为整数。

解决方案 2:

1. Declare three string (or array of chars) variables firstname, lastname and id
2. Declare six integers naming grade1 to grade6
3. Use the >> operator of ifstream to read into the values sequentially, that is, read to firstname, lastname, id, grade1,...grade6

>> 运算符应该处理字符串或整数问题,您也不必担心空格数。

如果您想避免 atoi,我不建议您避免,那么这里有一个将数字集合转换为数字的简单算法:

1. Let input = array of characters / string containing only numerical letters.
2. Set index = 0
3. Set sum = 0
4. While index is not beyond the last index at input
4.1. Set c = the character at index
4.2. Set value = ASCII value of c
4.3. Set sum = sum * 10 + value;
4.4. Increase index by 1
5. End-while

希望这有帮助:)

关于c++ - 将 C 字符串转换为 int 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21689636/

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