好的,这是我尝试读取的文件的文本:
KEYS
a set of keys
3
LAMP
a brightly shining brass lamp
8
ROD
a black rod with a rusty star
12
好吧,假装每行的间距均匀,但是在8和ROD之间有2条空行(或制表符)。我该如何跳过并继续该程序?我正在尝试将每一行放入3个向量中(因此将键,灯和杆放入一个向量中,等等)。这是我的代码(但它不会跳过空白行):
#include <string>
#include <iostream>
#include <sstream>
#include <vector>
#include <fstream>
using namespace std;
int main() {
ifstream objFile;
string inputName;
string outputName;
string header;
cout << "Enter image file name: ";
cin >> inputName;
objFile.open(inputName);
string name;
vector<string> name2;
string description;
vector<string> description2;
string initialLocation;
vector<string> initialLocation2;
string line;
if(objFile) {
while(!objFile.eof()){
getline(objFile, line);
name = line;
name2.push_back(name);
getline(objFile, line);
description = line;
description2.push_back(description);
getline(objFile, line);
initialLocation = line;
initialLocation2.push_back(initialLocation);
} else {
cout << "not working" << endl;
}
for (std::vector<string>::const_iterator i = name2.begin(); i != name2.end(); ++i)
std::cout << *i << ' ';
for (std::vector<string>::const_iterator i = description2.begin(); i != description2.end(); ++i)
std::cout << *i << ' ';
for (std::vector<string>::const_iterator i = initialLocation2.begin(); i != initialLocation2.end(); ++i)
std::cout << *i << ' ';
答案 0 :(得分:0)
您可以改用std::getline()
(正如许多人所指出的那样)...,它将逐行显示每一行: >
inline std::string ReadFile(std::ifstream& stream)
{
std::string contents;
std::string temporary;
while (std::getline(stream, temporary))
if (!std::all_of(temporary.begin(), temporary.end(), isspace))
contents.append(temporary + "\n");
return contents.substr(0, contents.size() - 1);
}
是的,示例:
int main()
{
std::ifstream is("file.txt");
if (is.fail())
return 1;
auto const contents = ReadFile(is);
is.close();
std::cout << contents << std::endl;
std::cin.get();
return 0;
}
答案 1 :(得分:0)
我认为您可以通过std::getline
检查字符串是否为空。如果是这样,那么您可以忽略它或类似的东西。
getline(objFile, line);
name = line;
while(name.length() == 0)
{
getline(objFile, line);
name = line;
}
name = line;
name2.push_back(name);
getline(objFile, line);
description= line;
while(description.length() == 0)
{
getline(objFile, line);
description = line;
}
description= line;
description2.push_back(description);
getline(objFile, line);
initialLocation = line;
while(initialLocation.length() == 0)
{
getline(objFile, line);
initialLocation = line;
}
initialLocation = line;
initialLocation2.push_back(initialLocation );
如果我是正确的,那么如果该行为空白,则该行将没有长度;如果是空白,我们将再次检查,因此将其忽略。