打印包含指定子字符串的所有字符串

时间:2014-02-28 20:29:11

标签: c++ c

我是c ++的初学者。我正在尝试实现一个小的c ++代码以获得乐趣。

程序从包含我所有朋友名字的文本文件中读取其输入。

该程序的目的是返回/打印以指定字母/昵称

开头的所有名称

例如

Nick 
Joseph
Jack
Robert 
Paul 
David

如果我输入'J',结果应该是Joseph和Jack

如果我输入'P'或'pa',结果应为paul

任何人都可以指导我使逻辑正确。提前谢谢了。

此致 帕

2 个答案:

答案 0 :(得分:1)

逻辑是这样的:

read the desired prefix from user
repeat
  read one line from file
  if the line starts with the desired prefix print it
until there are no more lines

答案 1 :(得分:0)

#include <iostream> 
#include <fstream> 

using namespace std; 

int main() 
{ 
  ifstream input; 
  input.open("words.txt");
  char word[80];
  char output;

  if (input.fail()) 
  { 
    cout << " the file doesnt exist" << endl;
    cout << " exit program" << endl; 

    return 0 ; 
  } 

  while ( !input.eof() ) 
  { 
    input >> output; 
    cout << output; 
  } 
  input.close();

  return 0; 
} 
相关问题