Hello people of the internet. I am currently learning how to program in c++ and I am having trouble with a program. This program is supposed to take in a string and write it out again wtih the ascii ordinance having a plus two i.e a = c or s = u. Whenever I run the program though the first character is taken in as a space and thus prints the character with the ascii ordinance of two. I am still pretty new to c++ so my code is pretty inefecient and all-around bad. Here is my code.

// ActivitySixPointOne.cpp : Defines the entry point for the console application.

#include "stdafx.h"
#include "stdio.h"
#include "conio.h"
#include <string>
#include <iostream>
using namespace std;

char Character;
string SubString;
int y;
string GetString()
    string SString;
    cout << "Please enter your string.\n";
    cin >> SString;
    return SString;
int _tmain(int argc, _TCHAR* argv[])
    string TString;
    int StringLength;
    StringLength = 0;
    TString = GetString();
    StringLength = TString.length();
    cout << "Your encoded string is.\n";
    for (int x = 1; x <= StringLength;x++)
        y = x - 1;
        SubString = TString.substr(y, y);
        Character = SubString[0];
        Character = _putch(Character + 2);  
    cout << "\n";
2 Years
Discussion Span
Last Post by NathanOliver

I should add that after the first character the rest of the program works fine.


line 32 you have SubString = TString.substr(y, y);
change the second y to x
SubString = TString.substr(y, x);

Edited by Captain119


This could be done very simply with the strings [] operator:

int main()
    std::string line;
    std::cout << "Please enter you string: ";
    getline(std::cin, line);

    // loop through each letter and add 2 to it while displayng it
    for(std::string::size_type i = 0; i < line.size(); ++i)
        std::cout << char(line[i] + 2);

    std::cin.get(); // use this to pause system.  not system("pause")
    return 0;

Thanks for the help. I was wondering though... why shouldn't I use system pause?

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.