2016-11-27 133 views
0

儘管問題的主題不太準確,但問題依然存在。我有一個文件,其中一個人寫他的文本,例如「今天是一個非常美好的一天」,我將它存儲在一個txt文檔中。然後,我的任務是把所有這些字符都移動一個字母(a變成b,z變成a等等)。但我需要保持空間在他們的地方。如何在數組中添加空格

#include <iostream> 
#include <fstream> 
#include <iomanip> 
#include <cmath> 

using namespace std; 

int main(){ 

string a; 
string Code; 
string New; 

ifstream File ("Txt.txt"); 
File>>Code; 

for (int i = 0; i<Code.size(); i++){ 
    if (Code.at(i) >= 'A' && Code.at(i) <= 'V' || Code.at(i) >= 'a' && Code.at(i) <= 'v') { 
      a = Code.at(i) + 4; 
      New += a; 
      } 
    else if (Code.at(i) == 'W'){ 
      a = 'A'; 
      New += a;} 
    else if (Code.at(i) == 'X'){ 
      a = 'B'; 
      New += a;} 
    else if (Code.at(i) == 'Y'){ 
      a = 'C'; 
      New += a;} 
    else if (Code.at(i) == 'Z'){ 
      a = 'D'; 
      New += a;} 
    else if (Code.at(i) == 'w'){ 
      a = 'a'; 
      New += a;} 
    else if (Code.at(i) == 'x'){ 
      a = 'b'; 
      New += a;} 
    else if (Code.at(i) == 'y'){ 
      a = 'c'; 
      New += a;} 
    else if (Code.at(i) == 'z'){ 
      a = 'd'; 
      New += a;} 
    else if (Code.at(i) == ' '){ 
      a = Code.at(i); 
      New += a; 
      } 
     }cout<<New; 

return 0; 
} 

但是程序只讀了第一個字。我應該如何改變程序來讀取所有空格的所有文本?

+2

你並不需要所有這些的'如果你意識到一個字母是模26。例如,如果字母是「Z」,因爲「z是26日的信,if'報表(26 + 1)mod 26 = 1,'a'是第一個字符。 – PaulMcKenzie

+0

我認爲這回答你的問題:http://stackoverflow.com/questions/37449872/how-to-read-in-multiple-words-from-a-text-file –

回答

1

使用std::getline,像這樣:

std::string line; 
std::ifstream file("file.txt"); 
std::getline(file, line); //loads one line 

順便說一句using namespace std;是一種不好的做法,你應該讓你的全局命名空間乾淨,使用std::前綴。如果你真的很懶,你可以只導入重要的部分。 using std::cin;

+0

它只是讀一行,然後你必須使用'std :: cout << line << std :: endl'。另外,如果你想加載所有的行,使用循環: ' –

+0

這完美的作品!非常感謝你! – Adversas

0

指向您的文件的末尾。

void openFile (ifstream& f) 
    { 
    const  long LINE_LEN = 23; 
    int pos; 
     // position to 256 lines before end of file 

f.open("demodoutcarr.txt"); 
f.seekg(0, ios::end); 
pos = f.tellg(); 
pos -= LINE_LEN * NBR_RECORDS; 
f.seekg(pos); 
    } 
+0

NBR_RECORDS沒有聲明,並且因爲我不瞭解代碼,所以我不知道如何修改它。你能幫我嗎? – Adversas

+0

嘗試像這樣打開文件,ifstream File(「Text」,ios :: in | ios :: ate); //最後 –