如何修复数组赋值从 ascii 值到 int

How to fix array assignment from ascii value to int

本文关键字:ascii 值到 int 赋值 何修复 数组      更新时间:2023-10-16

我正在使用指针遍历数组做家庭作业。当我去为数组分配一个 5 位邮政编码时,数组中填充了该数字的 ascii 值。我很难掌握指针的概念以及何时使用它们。

我已经在 eclipse 上使用调试工具来确定数组填充不正确,而不是我的输出语句。

以下是用于填充数组的方法,其中r1是类的对象,zipcode是大小为 5 的整数数组(出于测试目的,仅循环递增到 5(:

void getDataFromFile(RentalAgency &r1){
ifstream infile;
string input;
char number;
cout << "Enter the file name: ";
infile.open("Agencies.txt");
infile.get((r1.name),MAX_SIZE,space);
for(int i = 0;i < 5;i++){
infile >> number;
*(r1.zipcode+i) = number;
}
infile.close();
}

这是结构体RentalAgency的代码:

struct RentalAgency{
char name[MAX_SIZE];
int zipcode[5];
RentalCar inventory();
};

当给定数字 93619 时,预期输出为 93619,但实际输出为 57 51 54 49 57

看起来一切都是正确的。您正在读取字符并将其存储为整数。将值 57 打印为整数时,将打印数字本身。将 57 打印为字符时,将打印字符"9"(ASCII 值(。

您可以使用 将字符转换为 int

*(r1.zipcode+i) = number - '0';

C 和 C++ 保证无论使用什么表示形式,10 个十进制数字的表示形式都是连续的,并且按数字顺序排列,即使不使用 ASCII。

或者,您可以将邮政编码的数据类型从整数更改为字符:

char zipcode[5];

另外,我建议使用数组样式

r1.zipcode[i] = number;

它做同样的事情,但对于读者来说,程序员想要做什么更清楚一些。

如果将结构更改为

struct RentalAgency{
std::string name;
char zipcode[5];
RentalCar inventory();
};

您可以将功能简化为

void getDataFromFile(RentalAgency &r1){
std::ifstream infile;
std::string input;
std::cout << "Enter the file name: ";
std::cin >> input;
infile.open(input);
infile >> r1.name;
// or std::getline(infile, r1.name, space);
for (std::size_t i = 0; i < 5; ++i)
infile >> r.zipcode[i];
}
}

您可以拨打infile.close()但不需要它。当函数体离开时,也会在析构函数中调用它。

这是一个例子

#include <iostream>
#include <sstream>
#include <string>
struct RentalCar {};
struct RentalAgency{
std::string name;
char zipcode[5];
RentalCar inventory();
};
void getDataFromFile(RentalAgency &r1){
// std::ifstream infile;
// std::string input;
// std::cout << "Enter the file name: ";
// std::cin >> input;
// infile.open(input);
std::stringstream infile{"Name 12345 Name2 12346"};
infile >> r1.name;
for (std::size_t i = 0; i < 5; ++i)
infile >> r.zipcode[i];
}
}
int main() {
RentalAgency r;
getDataFromFile(r);
std::cout << r.name << ' ';
for (std::size_t i = 0; i < 5; ++i)
std::cout << r.zipcode[i];
}
std::cout << 'n';
// Output: Name 12345
return 0;
}