在C++中将ASCII读取到数组中
Read ASCII into array in C++
我是C++的新手,无法找到完成这项看似简单的任务的方法。我有一个ascii文件,只包含制表符分隔的数字,类似于:
1 2 5 6
8 9 1 3
5 9 2 3
我需要简单地使用c++将这个行一行地加载到一个数组中。什么是简单的方法?提前感谢!Niccolo
我无法发表评论,因为我还没有50的声誉,但我会尽我所能帮助你找到答案。
这需要对C++和循环有基本的理解。我认为最好的方法是同时使用std::vector
(因为您提到了C++)。
std::fstream
std::vector<char>
char
std::noskipws
vector.push_back
示例程序流程:
- 打开输入流
- 检查它是否打开
- 逐字符循环输入并使用
std::noskipws
- 在循环中,使用vector.push_back
- 记得关闭输入流
示例代码:
#include <iostream>
#include <fstream>
#include <vector>
int main(int argc, char *argv[])
{
//Use std::fstream for opening and reading the file.txt
std::fstream Input("file.txt", std::fstream::in);
//If the input stream is open...
if(Input.is_open())
{
//...Create variables
char ch;
std::vector<char> cVector;
//Loop trough the Input, character by characted and make use of std::noskipws
while(Input >> std::noskipws >> ch)
{
//Push the char ch to the vector
cVector.push_back(ch);
}
//This is for looping through the vector, and printing the content as it is
for(auto i : cVector)
{
std::cout << i;
}
//Remember to close the input
Input.close();
}
//Prevent application from closing instantly
std::cin.ignore(2);
return 0;
}
希望我帮了你,这就解决了问题。但如果下次你能解释一下你遇到了什么问题,以及你尝试了什么,我将不胜感激。
谨致问候,Okkaaj
相关文章:
- 从锯齿状数组读取
- 是否很好地定义了强制转换为仅由 char[] 组成的结构并从该数组读取?
- 如何按字符从文件到2D数组读取字符
- 双维数组读取错误
- 动态分配的数组C 读取句子并打印单词
- ESP8266异常在尝试从字节数组读取float时
- C++无法从 2D 字符串数组读取
- Win32 C/C++从字节数组读取BMP宽度和高度
- 在执行期间将大型多维数组读取和写入二进制文件并返回数组
- 从 BYTE 数组读取 32 位整数.VC++
- 从十六进制数组读取 Int
- 从十六进制数组读取双精度到向量
- 通过数组C++读取学生的成绩
- 使用迭代器数组读取稀疏信息
- 从文件到字符串再到数组读取数字
- 直接从数组读取时超出了绑定地址
- 转换为空指针后从char数组读取int值
- 动态数组读取
- 从字节数组读取类型的模板方法的问题
- 从文件中以单独的数组读取整数,每次一个数字,在c++中