variable is not permanently added
Dec 14, 2018 at 4:06am UTC
Hello. I am trying to create a piece of code that takes an input from the user, and sends it similar to a pyramid. For example,
Input: Bear
B
Be
Bea
Bear
Bea
Be
B
But when spaces are added, this happens
Input: Teddy Bear
T
Te
Ted
Tedd
Teddy
Teddy // As you can see, it doesn't switch over to the next letter
Teddy B
I am sorry if this may sound confusing. There is a comment in my code explaining this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
string fileName = "testing.txt" ;
ofstream outputFile;
outputFile.open(fileName);
if (outputFile.is_open())
{
string characters;
cout << "Enter the string of words" << endl;
getline(cin, characters);
for (int i = 0; i < characters.length(); i++)
{
for (int j = 0; j < i; j++)
{
if (characters[j] != ' ' )
outputFile << characters[j];
else if (characters[j + 1] == ' ' ) // j is not permanently added by 1
outputFile << characters[j];
}
if (i != 0)
outputFile << endl;
}
for (int j = characters.length(); j >= 0; j--)
{
for (int x = 0; x < j; x++)
{
if (characters[x] != ' ' )
outputFile << characters[x];
}
outputFile << endl;
}
outputFile.close();
}
else
cout << "File " << fileName << " not opened" << endl;
cin.get();
return 0;
}
Dec 14, 2018 at 4:15am UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
#include <string>
#include <cctype>
int main()
{
std::string line;
std::getline(std::cin, line);
for (std::string::size_type i = 0; i < line.size(); ++i)
{
if (std::isspace(line[i]))
continue ;
std::cout << line.substr(0, i + 1) << '\n' ;
}
}
Live demo:
http://coliru.stacked-crooked.com/a/d6a4ec98fa7cf949
Last edited on Dec 14, 2018 at 4:15am UTC
Topic archived. No new replies allowed.