如何修复数组赋值从 ascii 值到 int
How to fix array assignment from ascii value to int
我正在使用指针遍历数组做家庭作业。当我去为数组分配一个 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;
}
相关文章:
- HEX值到wchar_t字符(UTF-8)的转换
- 值到类型的运行时映射
- 使用指针将 ASCII 值添加到整数
- 在 constexpr 构造函数 (c++17) 中赋值到 const char * 在使用 Android NDK 时
- 如何防止双精度值到整数的隐式转换
- 无符号字符打印其 ASCII 值
- 赋值到类型和空大括号. 语法说明
- 在结构数据类型中更改每个字符的 ASCII 值
- 返回对常量结构(指针类型)成员的引用:明显的左值到右值转换
- 如何线性插值到不恒定的目的地
- 从类型bankAccount的返回值到函数返回类型int没有可行的转换
- 在Qt中将QString转换为ASCII值,反之亦然
- 如果在开关情况下不匹配,为什么此函数返回 ASCII 值?
- 如何修复数组赋值从 ascii 值到 int
- 从自身内部替换 std::函数(通过将移动赋值到 *this?)
- 用于增加 ASCII 值的循环
- 如何将值从指针永久赋值到变量
- 读取字符 ASCII 值并将其记录到矢量
- 在 c# 中将 int 添加到字符以将其 ascii 值向上移动(就像在 c++ 中一样)
- 我如何从ASCII转换到十六进制值,也增加char指针