sample.txt
The contents of are
Apple=150
range=300
grape=200
when
I would like to, but with the code below, I will get stuck in else if(key!="grape")
whether there is a scrap or not.
If there is a scrap, how should I fix it to avoid getting stuck in else if(key!="grape")
?
I would like to start processing else if(key!="grape")
only if there is no grape or if the grape is spelled incorrectly (for example, grape).
#include "MainWindow.h"
# include <QApplication>
# include <QDebug>
# include <QFile>
# include <QTextCodec>
int main(intargc, char*argv[])
{
// QApplication a(argc,argv);
// MainWindow;
// w.show();
QFile file("C:\\Users\\Desktop\\sample.txt";
if(!file.open(QIODevice::ReadOnly))
{
qDebug()<<"can not open file.";
return 0;
}
QString str;
QTextStream in (&file);
str = in.readAll();
qDebug()<<str;
QStringList list1 = str.split("\n");
for(inti=0;i<list1.count();i++){
QString txt = list1[i];
QStringList list2 = txt.split("=");
QString key=list2[0];
QString value = list2[1];
if(key=="apple"){
qDebug()<<"correct";
}
if(key=="grape"){
qDebug()<<"correct";
}
else if(key!="grape"){
qDebug()<<"incorrect";
// break;
}
if(key=="orange"){
qDebug()<<"correct";
}
}
file.close();
// return a.exec();
}
This is not a title-like split for Qt, but a common C++ programming problem.
The three if
statements in the for
loop are not skipped with break
or continue
or summarized with else if
, else
and are all applicable to the processing.
For example, apple
and orange
are all checked for apple
, grape
, or orange
.
Therefore, qDebug()<<"incorrect";
will run as not
.
Strictly organize what you want to check and process
For example, grape
, grape
, grepe
, grapu
, and so on, as well as apple
, or orange
(or lemon
.
In that sense, it would not be appropriate to make a decision based on the condition that "Isn't it grape
?"
Program accordingly by carefully organizing what data is and how to process it (what is or isn't, how to determine and how to handle when there is data that isn't).
How do you do it with less changes?
You can do the following.
(If the conditions increase or decrease in the above arrangement, we will change them accordingly.)
apple
, grape
, orange
, Other
(stop judging that it is not grape
)if
, else if
, else
so that no other decision can be made once one of them is establishedgrape
to initialize with false before the for
loop, set true if found in the for
loop, and check for grape
with flag variables after the loop ends
© 2024 OneMinuteCode. All rights reserved.