2016-12-28 243 views
-4

我需要帮助。我想写的程序,打开文件在哪里是问题,并通过问题阅读问题,文件中的问题从<开始,并以>如何与类如何做? 我想程序去一个问题,然后你回答你后得到下一个问题。 现在我这样做: `C++逐行读取文件

int main() { 
    ifstream myfile; 
    myfile.open ("21fundamentalvariabletypes.txt"); 
    while (myfile){ 
    int i = 1; 
    string strInput; 
    getline(myfile, strInput); 
    if (strInput == "<") { 
     cout << i << "."; 
     i++; 
    } 
    if (strInput == ">") { 
     cout << endl; 
    } 
    else { 
     cout << strInput << endl; 
     i++; 
    } 
    } 
    return 0; 
} 

和我得到这个屏幕上:

1. < STA济ispravan nacin deklaracije promenljive? - a = 4; * int a; - int a = 4; - int a = 4

1. < Povezati ispravan par? - 1 AA - 2 BB - 3 CD - 4哒 * 1-> 3 * 2-> 3 * 3-> 4 * 4-> 1

为什么犯规我++工作,并为什么我第一次有1. <。但是,当我不把if (strInput == ">")等,然后我有1,然后质疑

+2

我们不打算写一个完整的程序给你。写下你的逻辑,并在这里提出任何技术问题。 – Ryan

+0

你问了一个东西的教程,你可以很容易地在谷歌发现 –

+0

看看'fopen','fgets','fclose'都在手册页#3 –

回答

0

好,如果你想读的问题的问题,你可以做这样的事情:

int i = 0; 
for(; i < line.size(); i++){ 
    if(line[i] == "<") break; 
} 
bool foundEnd = false; 
int j = i + 1; 
while(1){ 
    for(; j < line.size(); j++){ 
     if(line[j] == ">"){ 
      foundEnd = true; 
      break; 
     } 
    } 
    if(!foundEnd) {getline(myfile, line); j = 0;} 
    else break;  
} 
return the whole text from i to j 

一步一步,你可以从我Concat的线条到j,并得到你的问题

0

为什么你创建的字符串inputi内循环?这意味着每读完一行后,这些变量将被重置,以便在循环之外声明它们。

你的情况

可以,只要这个问题可能包含多个行,以便该字符的每个输入将被扫描是否是<>第一每次只读一个字符,使一个逻辑变量真正为这个问题的一个标志已经开始了,后者是问题结束的标志,它是Xors isBegin

,使问题的阵列和感觉它:

#include <iostream> 
#include <fstream> 
#include <string> 
using namespace std; 


int main() 
{ 

    char c; 
    bool isBegin = false; 
    string sQuestion[10]; 

    ifstream in("data.txt"); 

    int i = 0; 
    while(in >> c) // read character by character 
    { 
     if('<' == c) // if so then it's a sign of beginning of question so set the logical variable isBegin to true 
     { 
      isBegin = true; // set it to true 
      continue; // in order not to add '<' to the question  
     } 
     else 
      if('>' == c) // if so it is a sign of end of question 
      { 
       isBegin = false; // so set it to false 
       i++; // move to next quesiton and store it in the next element in the array 
      } 
     if(isBegin) 
      sQuestion[i] += c; // filling the question 
    } 

    // checking 
    for(int i(0); i < 10; i++) 
     cout << sQuestion[i] << endl; 

    in.close(); 

    cout << endl; 
    return 0; 
} 
  • ,如果你愿意,你可以阅读首次文件来计算的题数,然后创建的问题和最后一个动态数组将文件重新填充以填充每个问题。
+0

是的这个作品,但没有间距 – Zolak94

+0

@ Zolak94:什么间距? – Raindrop7

+0

当我开始代码他加载一切,但没有词之间的空间。 – Zolak94