对不起,我很抱歉。这是经过测试和重现的。
我正在尝试让 cout 在fstream中循环工作,同时检测每个字符的解析,但它表现出一种奇怪的行为,文本被第一个变量覆盖,我是试图投入cout。
main.cxx
#include <string.h>
#include <fstream>
#include <iostream>
#include <stdio.h>
using std::string;
using std::fstream;
using std::noskipws;
using std::cout;
int main(int argc, const char *argv[]){
char pipe;
string word; // stores the word of characters it's working on at the moment
string filename = "Directory.dat";
int type = 0; // 2 types counter, starts at 0
int newindicator = 0; // for detecting a new * for the data set
fstream fin(filename.c_str(), fstream::in);
while(fin >> noskipws >> pipe){
if(pipe == '*'){ // if the character is an asterisk
type++;
newindicator = 0;
word.clear();
}else if (pipe == '\n'){ // if the character is next line
if(newindicator == 0){ // tells the reader to know that it just finished reading a *, so it doesn't print anything.
newindicator = 1;
}else {
if(type == 1){
cout << "new word as: ";
cout << word << "\n";
}else if (type == 2){
cout << "new word as: ";
cout << word << "\n";
}
word.clear(); // clears the word string as it's reading the next line.
}
}else{
word+=pipe;
}
}
return 0;
}
Directory.dat
*
Chan
Johnathan
Joespeh
*
Betty
Lady Gaga
输出
Chanword as:
new word as: Johnathan
new word as: Joespeh
Bettyord as:
new word as: Lady Gaga
请注意,“Chan”如何覆盖第一行的“new”字符,但之后就好了。这似乎发生在我正在做的每一种新类型上,当它召回一组新的类型时。与下一组中的Betty相同,在该cout上用“Betty”覆盖“new w”。
任何反馈都会非常感激。谢谢!
答案 0 :(得分:0)
我怀疑你的输入文件有Windows行结尾。它们包含在Unix上以不同方式处理的回车符。
https://superuser.com/questions/374028/how-are-n-and-r-handled-differently-on-linux-and-windows
答案 1 :(得分:0)
感谢大家的意见和反馈。根据建议做出改变:
<强>校正的强>
#include <string.h>
#include <fstream>
#include <iostream>
#include <stdio.h>
using std::string;
using std::fstream;
using std::noskipws;
using std::cout;
int main(int argc, const char *argv[]){
char pipe;
string word; // stores the word of characters it's working on at the moment
string filename = "Directory.dat";
int type = 0; // 2 types counter, starts at 0
int newindicator = 0; // for detecting a new * for the data set
fstream fin(filename.c_str(), fstream::in);
while(fin >> noskipws >> pipe){
if(pipe == '*'){ // if the character is an asterisk
type++;
newindicator = 0;
word.clear();
}else if (pipe == '\n'){ // if the character is next line
if(newindicator == 0){ // tells the reader to know that it just finished reading a *, so it doesn't print anything.
newindicator = 1;
}else {
if(type == 1){
cout << "new word as: ";
cout << word << "\n";
}else if (type == 2){
cout << "new word as: ";
cout << word << "\n";
}
word.clear(); // clears the word string as it's reading the next line.
}
}else{
if (pipe != '\r'){
word+=pipe;
}
}
}
return 0;
}
<强>输出强>
new word as: Chan
new word as: Johnathan
new word as: Joespeh
new word as: Betty
new word as: Lady Gaga