我有一个名为text.cpp的文件。我的任务是从文件中读取的。
text.cpp文件(在文件内部)
#include <iostream>
#include <cstring>
#include <ctype.h>
#include "program.h"
#include "binarytree.h"
#include "linkedlist.h"
当我检测到
'#' symbol
系统将开始循环,如果它检测到'<' & '"'
符号,则将打印出剩余的单词。示例输出:iostraem
我可以检测'<'
符号并打印输出成功。但是,当我检测到'"'
符号时,我可以打印剩余的单词(program.h
),但它会紧跟烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫
该单词的后面。
我可以知道我的代码有什么问题吗?
我的代码如下:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{ char temPlate[100];
char FileName[20];
cout << "Enter Filename:" ;
cin >> FileName;
fstream read(FileName);
if (read.is_open())
{
while(!read.eof())
{
read.getline(temPlate, 100);
for (int k = 0; k < 100 ;k++)
{
if(temPlate[k] == '#')
{
for(int i = 0; i < 100; i++)
{
if(temPlate[i] == '<' || temPlate[i] == '"')
{
for (int j = i+1; j < 100; j++)
{
if(temPlate[j] == '>' || temPlate[j] == '"')
{
break;
}
cout << temPlate[j];
}
cout <<endl;
}
}
}
}
}
}
else
{
cout << "File does not exist, press enter to exit the program." << endl;
system("pause");
exit(EXIT_SUCCESS);
}
system("pause");
}
输出:
Enter FileName: text.cpp
iostream
cstring
ctype.h
program.h
ype.h
binarytree.h
烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫
linkedlist.h
烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫
这确实比需要的要复杂得多。您可能会考虑这样的事情:
#include <iostream>
#include <string>
#include <fstream>
int main()
{
std::string inputFilename;
std::cout << "Enter Filename:";
std::cin >> inputFilename;
std::ifstream inputFile(inputFilename);
if(inputFile)
{
std::string line;
while(std::getline(inputFile, line))
{
if(line.find('#') != std::string::npos)
{
size_t startPos = line.find_first_of("<\"");
size_t endPos = line.find_last_of(">\"");
if(startPos != std::string::npos && endPos != std::string::npos)
{
//advance start to after the < or "
++startPos;
//sanity check just in case the line was ill formed
if(startPos < endPos)
{
std::cout << line.substr(startPos, endPos - startPos) << std::endl;
}
}
}
}
}
else
{
std::cout << "File '" << inputFilename << "' does not exist." << std::endl;
}
return 0;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句