如何逐行读取文本文件中的字符串
how to read line by line string in a text file?
此代码将仅读取和计算输入.txt文件中的第一个输入,并忽略输入文件中的其余输入。我一直在尝试解决它,以便它可以读取所有其他输入并计算它们。这是我的代码,我认为它有问题。
我尝试了几种循环方法
int main()
{
string inputLine;
ifstream file ("input.txt");// input file to be read
ofstream file1;
file1.open("output.txt");
freopen("output.txt", "w", stdout);// store all the output to this file
while (std::getline (file, inputLine)) // read the strings in the input file
{
if( strncmp( "----", inputLine.c_str(), 4 ) == 0 )
continue;
//calculating binary and hexadecimal values
char *opr = "^+-/%*=,()";
std::string::iterator end_pos = std::remove(inputLine.begin(),
inputLine.end(), ' ');
inputLine.erase(end_pos, inputLine.end());
string str=inputLine;
string str2="";
int length=str.length();
char t[length];
str.copy(t, length);
t[length] = ' ';
char* tok;
char *cop=new char [length];
str.copy(cop,length);
char *w = strtok_fixed( t, opr );
while (w!=NULL)
{
string w2=w;
std::stringstream tr;
tr << w2;
w2.clear();
tr >> w2;
int x=w2.length();
int y=x-3;
string check= w2.substr(0,3);
string check1=w2.substr(0,x);
if(check.find("0x") != std::string::npos)
{
unsigned int x= strtol(w2.c_str(), NULL, 0);
std::ostringstream s;
s << x;
const std::string ii(s.str());
str2=str2+ ii;
}
else if (check1.find("b")!=std::string::npos)
{
w2.pop_back();
long bin=std::strtol(w2.c_str(),0,2);
std::ostringstream s2;
s2<<bin;
const std::string t2(s2.str());
//inputLine.replace(inputLine.find(w2),(w2.length()+1),t2);
str2=str2+t2;
}
else
{
str2=str2+w2;
}
char a =cop[w-t+strlen(w)];
string s1="";
s1=s1+a;
std::stringstream tr1;
tr1 << s1;
s1.clear();
tr1 >> s1;
str2=str2+s1;
w = strtok_fixed (NULL, opr);
}
//str2 should be taken to the parser for final evaluations
Parser p(str2);
double value = p.Evaluate ();
std::cout<<"----------------------"<<endl;
std::cout << "Result = " << value << std::endl;
std::cout<<"----------------------"<<endl;
return 0;
}
}
问题出在最后
return 0;
}
}
应该是
}
return 0;
}
您是从 while 循环内部返回的,而不是在 while 循环完成后返回的。
您应该花时间正确缩进代码。它将帮助您发现此类错误。您还应该学会将代码分解为较小的函数。同样,这将帮助您更好地理解自己的代码。
相关文章:
- 读取大文件(>2GB)(文本文件包含以太网数据)并通过不同参数随机访问数据的最佳方法是什么?
- C++程序不返回文件中文本和字符串数据的值
- 提升配置文件的文本文件接收器设置
- 随机访问文件格式,用于分层组织的二进制文件和文本文件
- 是否可以使头文件使文本居中?- 在控制台中
- 如何为包含其他 protobuf 的 protobuf 文件编写文本
- 使用strtok_s显示来自文本文件的文本
- 根据某些输入文件预测文本生成'random'下一个字符
- 从二进制文件中抓取文本时,为什么 xdg_vtnr=8 是我的结果
- 我怎么知道我是在读二进制文件还是文本文件
- 如何在wxWidgets的同一窗口中拖放文件和文本
- 二进制文件到文本文件,文本文件到二进制文件
- 无法从文件打印文本
- 设置新文件默认文本
- C++显示文本文件...("Echo"文本文件)
- 从Windows应用程序的文本框中抓取文本
- 音频文件到文本使用SAPI或同等功能的SR
- 对于大文件,文本文件中的大多数常用词从未完成
- 通过套接字发送文件和文本
- 从文件读取文本到无符号字符数组