[英]error reading data from input file to array
输入文件包含14个状态首字母(TN,CA,NB,FL等),应将其放入阵列中。 下面的代码清除了编译器,但是当我告诉程序文件名时,它将射出一堆空格,其中两个空格包含一些绒毛,第三个空格包含一个“ @”符号。 我认为问题出在我的功能上,虽然可以得到任何帮助,但不能完全确定到底有什么帮助!
输入文件,其中一个以状态开头,一个在另一个上:
TN PA KY MN CA等
void readstate( ifstream& input, string []);
int main()
{
string stateInitials[14];
char filename[256];
ifstream input;
cout << "Enter file name: ";
cin >> filename;
input.open( filename );
if ( input.fail())
{
cout << " file open fail" << endl;
}
readstate ( input, stateInitials);
input.close();
return (0);
}
void readstate ( ifstream& input, string stateInitials[])
{
int count;
for ( count = 0; count <= MAX_ENTRIES; count++)
{
input >> stateInitials[count];
cout << stateInitials[count] << endl;
}
}
您正在将字符数组视为字符串数组。 虽然您可以在相同的char
数组中修改字符串的位置,但是这并不是标准的方法。 这是代码的修改版本,该代码创建一个char[]
来保存每个缩写。
#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>
#include <string.h>
#define MAX_ENTRIES 14
using namespace std;
void readstate( ifstream& input, char* []);
int main()
{
char** stateInitials = new char*[14];
char filename[256];
ifstream input;
cout << "Enter file name: ";
cin >> filename;
input.open( filename );
if ( input.fail())
{
cout << " file open fail" << endl;
}
readstate ( input, stateInitials);
// After you are done, you should clean up
for ( int i = 0; i <= MAX_ENTRIES; i++) delete stateInitials[i];
delete stateInitials;
return (0);
}
void readstate ( ifstream& input, char* stateInitials[])
{
int count;
string temp_buf;
for ( count = 0; count <= MAX_ENTRIES; count++)
{
stateInitials[count] = new char[3];
input >> temp_buf;
memcpy(stateInitials[count], temp_buf.c_str(), 3);
cout << stateInitials[count] << endl;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.