我在文件中有少量数据,看起来像
新墨西哥州 50.9 10
这与每个州都重复,每当我用两个单词为其标题命中状态时,我的程序就会说ooops我们会在你的字符串中放入第一个单词,但第二个单词没有存储空间。因此,一旦遇到双重措辞的标题,它就会停止接收剩余的数据。有没有办法在读取我的文件时把两个单词放在一个字符串中?
#include <iostream>
#include <string>
#include <fstream>
#include <cstring>
using namespace std;
struct AccountsDataBase{
string stateName;
double miles;
int rests;
};
#define MAX 80
AccountsDataBase * account = new AccountsDataBase[MAX];
int readIn(ifstream& file){
int count=0;
file >> account[count].stateName;
file >> account[count].miles;
file >> account[count].rests;
while( !file.eof() && count<MAX){
count++;
file >> account[count].stateName;
file >> account[count].miles;
file >> account[count].rests;
}
return count;
}
int main(){
ifstream file;
file.open("input.txt"); //opens data account records text
if ( !file.fail() ) {
int cnt = readIn(file);
delete[] account;
}
return 0;
}
答案 0 :(得分:3)
你的问题肯定含糊不清。但是,这是一种方法:
std::ifstream ifile("filename_and_path"); //Requires <fstream>
//check to see if the file is open or not:
if (!ifile.is_open()) {
std::cerr << "Something went wrong!" << std::endl;
exit(1);//stop program execution. Requires <cstdlib>
}
std::string temp;
std::string state;
std::vector <std::string> tokens; //Requires <vector>
//std::getline requires: <string>
while(std::getline(ifile, temp)) {
std::istringstream iss(temp);//initialize the stream to the contents of the line
//keep parsing over the stream into tokens separated by ' ' (space) characters
while(std::getline(iss, temp, ' ')) {
//store all the tokens:
tokens.push_back(temp);
}
//UPDATED to read ALL states. (I misread the question.)
//we know that the last two parameters are always numbers, so use this
//to our advantage:
//if an even number, then we have two words, get and concatenate them:
if (tokens.size() % 2 == 0) {
state = tokens[0] + " " + tokens[1];
}
else {
//this is an odd number of parameters. This means that this is a state
//with one word (e.g.: Maryland)
state = tokens[0];
}
//this is the end of one line, might as well print out the state name:
std::cout << state << std::endl;
state.clear();//empty the string for the next iteration
tokens.clear();//empty the tokens for the next iteration
}
答案 1 :(得分:0)
您可以使用std :: vector存储每行中的所有std :: string标记,然后使用迭代器读取值。只要文件中每行的最后两个标记代表double和int值,此解决方案适用于任何长度的一般状态名称,而不仅仅是像新墨西哥这样的双字的一个。
int readin(const ifstream& file)
{
...
string val;
vector<string> v;
while (val = file.get() )
{
v.push_back(val);
}
//assign concatentaion from element 1st to nth-2
for(vector<string>::iterator it = v.begin(), it != v.end()-2;it++)
account[count].stateName += *it + " ";
//assign element nth -2
account[count].miles = atof(*(v.end()-2).c_str());
//assign element nth -1
account[count].rests = atoi(*(v.end()-1).c_str());
...
}
答案 2 :(得分:0)
好的每个人我都问我的老师答案,她说我所要做的就是使用getline(); D解决我的问题,即将应用20行代码来解决单行C函数问题。