Hello, In the following program a user enters a string and then enters a number. The number will return that amount of characters in the string. It works great if the amount of characters in the string is larger than the number entered.
Example:
Input string: Michelle
Input number: 4
output: Mich
However, if the number entered is larger than the string, then the program crashes.
Example:
Input string: Michelle
Input Number: 15
output: End of days
I'm hoping to fix this so that if the number entered is larger than the string, the string is returned, followed by blank spaces for the remaining width entered.
Yes, but I would like to fill in the remaining spaces with blanks. Basically I'm trying to place multiple strings on one line that have a maximum size, but do not effect each others placement...
Okay. a.append() a space within a loop that iterates the difference of ctr and a.length() times when the conditional statement (as explained above) evaluates to true.
If ctr > a.length() then the difference would be the amount of spaces placed before your cout << "|" so that with your example:
Input string: Michelle
Input Number: 15
... you would end up with 7 blanks:
Michelle_______|
I think you are set. Is any of this helping? I may very well not be understanding something you want here.
difference = ctr - a.length()
loop until i == difference {
a.append(" ")
} i++;
...then your for loop using a.at() from your code above.
EDIT: You threw in something as I posted the pseudo-code.
You can throw out a variable or two and do this:
1 2 3 4 5 6 7 8 9
// set spaces when user input for width is greater than string
if(width > a.length()) {
for(int i = a.length + 1; i < width; i ++)
a.append(" ");
}
// print to screen
for(int i = 0; i < a.length(); i++)
cout << a.at(i)
The logic is correct, but you may need to tweak this to make sure it compiles.
if ( ctr > a.length() ) // the conditional
{
cout << " "; // out the space, you can use whichever form of space you want.
}
else
{
cout << a.at(ctr);
}
What I came up with seems to be working fine, but I wouldn't have been able to do it without the append() function. Thank you very much for you help. Again though, I'm new so I'm not quite sure what you mean by redundancy. Could you explain please?
What you need to understand is that a string is a complex array of characters.
If you want element 2 of the string, then string[1] will return it as a character.
Append adds another element with the character you have in parenthesis.
The code he gave you will simply add spaces to the end of the original string if the number is larger than the strings length. After that, it displays the entire string in one go.
If you want to display one character at a time, use my code in the for loop of your original post.