0

While the topic of the question isn't quite accurate, here's the problem. I have a file in which a person writes his text, for example 'Today is a very nice day' and i store it in a txt document. Then my task is to take all of these charaters and move them one letter further (a becomes b, z becomes a and so on). But I need to keep the spaces in their places.

#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;
}

But the program only read the first word. How should I change the program to read all the text with all the spaces?

Adversas
  • 13
  • 1
  • 6
  • 2
    You don't need all of those `if` statements if you realized that the next letter is modulo 26. For example, if the letter is 'z', since 'z is the 26th letter, (26 + 1) mod 26 = 1, and 'a' is the first character. – PaulMcKenzie Nov 27 '16 at 18:54
  • I think this answers your question: http://stackoverflow.com/questions/37449872/how-to-read-in-multiple-words-from-a-text-file – Maxim Chetrusca Nov 27 '16 at 18:59

2 Answers2

1

Use std::getline, like this:

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

Btw using namespace std; is a bad practice, you should keep your global namespace clean and use std:: prefix. If you are really lazy, you can 'import' only important parts. using std::cin; etc.

Kamil Koczurek
  • 696
  • 5
  • 15
  • It just reads one line, then you have to use `std::cout << line << std::endl`. Also, if you want to load all the lines, use a loop: ` – Kamil Koczurek Nov 27 '16 at 19:32
0

Point at the end of your file.

 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);
  }