输入文件包含要放入数组的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;
}
}
答案 0 :(得分:0)
您将字符数组视为字符串数组。
虽然你可以将字符串放在同一个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;
}
}