2014-02-28 148 views
-1

我是C++的初學者。我正在嘗試實現一個小型的C++代碼,以獲得樂趣。打印包含指定子字符串的所有字符串

該程序從包含我所有朋友的名字的文本文件讀取其輸入。

該計劃的目的是返回/打印與指定的信/暱稱開頭的所有名稱

例如

Nick 
Joseph 
Jack 
Robert 
Paul 
David 

如果我輸入「J」的結果應該是約瑟和傑克

,如果我輸入「P」或「啪」的結果應該是保羅

任何一個可以請指導我獲得邏輯正確的。提前謝謝了。

問候, 帕

+0

那你試試? –

+1

你已經有了基本的邏輯集。您只需要a)提示輸入b)接受輸入c)搜索輸入的字符串d)報告結果。 –

+0

#include #include using namespace std; int main() { ifstream input; input.open(「words.txt」); char word [80]; 字符輸出; (input.fail()) cout <<「文件不存在」<< endl; cout <<「exit program」<< endl; return 0; } while(!input.eof()) { input >> output; cout << output; } input.close(); return 0; } – user3366438

回答

1

THS 邏輯是這樣的:

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 
+0

#include #include using namespace std; int main(){ifstream input; input.open(「words.txt」);字符[80];字符輸出; if(input.fail()){cout <<「文件不存在」<< endl; cout <<「exit program」<< endl;返回0; } while(!input.eof()){input >> output; cout <<輸出; } input.close();返回0; } – user3366438

+0

Hi @Michael,非常感謝Logic。如何使用for循環掃描文本文件中的每一行以獲取用戶所需的輸入?請幫忙!你可以指導我的代碼請!謝謝 – user3366438

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; 
} 
相關問題