【问题标题】:file handling : displaying content within comment/quotes文件处理:在评论/引号中显示内容
【发布时间】:2012-04-18 02:42:06
【问题描述】:

我正在编写一个 C++ 程序来显示文本文件中引号或单行或多行注释内的任何文本。问题是我不能让它正常运行。这是我的程序:

#include <iostream.h>
#include <fstream.h>
#include <string.h>
#include<conio.h>
using namespace std;

int main () {
    char ch, name[20];
    int count=0;
    fstream fin;
    cin>>name;
    fin.open(file_name, ios::in);
    while(!fin.eof()) {
        fin.get(ch);
        if(ch=='/') {
            fin.get(ch);
            if(ch=='*') { 
                a:
                fin.get(ch);
                while(ch!='*') {
                    cout<<ch;
                    fin.get(ch);
                }
                fin.get(ch);
                if(ch!='/') goto a;                                 
            }
            if(ch=='/') {
                fin.get(ch);
                while(ch!='\n') {
                    cout<<ch;
                    fin.get(ch);              
                }
            }
        }
    }

    getch(); 
    return 0;
}

edit:它陷入无限循环。我知道如何。 问题仍然存在。我正在使用 Dev C++ 编辑器。

【问题讨论】:

  • 不是针对您的特定问题的解决方案,而是将name 声明为chars 的原始数组,将其声明为string 以避免可能的溢出
  • 无法正常运行是什么意思?它在什么输入上失败?它对该输入产生什么影响?
  • 那个 label/goto 可以很容易地被循环替换,这样会好很多。

标签: c++ file-handling


【解决方案1】:

无限循环需要循环。您的代码中有两个循环。第一个while(!fin.eof()) { 不会导致无限循环,因为文件最终会被耗尽。

所以我们仍然使用内部循环和 goto 语句。 我认为逻辑中存在一个错误 - 如果星号后没有斜线,则循环将永远不会结束。

【讨论】:

  • 感谢您的回复。我一遍又一遍地研究它。即使星号后面有斜线,它也会打印出无限的斜线。
猜你喜欢
  • 1970-01-01
  • 2019-08-08
  • 2017-09-15
  • 2019-12-07
  • 1970-01-01
  • 2014-01-04
  • 1970-01-01
  • 2016-03-17
  • 2013-06-05
相关资源
最近更新 更多