2016-11-27 129 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); //最后 –