Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 months ago.
This post was edited and submitted for review 3 months ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
I'm having problems with this simple example.
The program inquires as to how many letters are required to form a complete word. Then it will ask for each letter individually, which is fine, but I can't make the code save the value from the current character and the next one from the next iteration until the number of letters finishes the word and print it to confirm the word.
E.g. Let's say house, which has 5 letters.
int numbersOfCharacters=5;
int counter=0;
char character;
string phrase;
while (counter < numbersOfCharacters)
{
cout << "Introduce character's number" << counter << ": ";
cin >> character;
counter = counter + 1;
phrase=character+character; //I'm not sure if I need an array here.
}
cout << "Concatenated characters: " << phrase << endl;
The output is:
Introduce the character number 1: h
Introduce the character number 2: o
Introduce the character number 3: u
Introduce the character number 4: s
Introduce the character number 5: e
Concatenated characters: ?
And the expected output should be:
Concatenated characters: house
Update
Using John's comments I was able to resolve the issue. It's not a lack of debugging information but instead know the proper operator for this solution. Thanks also to Remy Lebeau for the detailed info.
The expression phrase=character+character; doesn't do what you think it does. You are taking the user's input, adding its numeric value to itself, and then assigning (not appending) that numeric result as a char to the string.
So, for example, on the 1st iteration, the letter h has an ASCII value of 104, which you double to 208, which is outside the ASCII range. On the next iteration, the letter o is ASCII 111 which you double to 222, which is also outside of ASCII. And so on. That is why the final string is not house like you are expecting.
Perhaps you meant to use phrase=phrase+character; instead? But, that won't work either, because you can't concatenate a char value directly to a string object using operator+.
What you can do is use string::operator+= instead:
phrase += character;
Or the string::push_back() method:
phrase.push_back(character);
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
Here in this code, when I'm entering inputs one by one, I'm getting correct output as expected(correct size of string using std::string.size()), But when I'm entering three or four inputs together(or entering input in bulk) the output (size of string) gets incremented by 2.
Ps: Look once at attached output snippets.
#include <iostream>
int main()
{
int count;
std::cin >> count;
std::cin.ignore();
while (count--)
{
std::string s;
std::getline(std::cin, s);
std::cout << s.size() << '\n';
}
return (0);
}
Edit: I have printed all inputted string and found that at the end, the extra characters are two blank-spaces, as you can see below, (though I tried so far, but still don't know the reason):
5
</h1>
</h1> 7
Clearly_Invalid
Clearly_Invalid 17
</singlabharat>
</singlabharat> 17
</5>
</5> 6
<//aA>
std::cin.ignore(); ignores characters to the EOF. When you enter one line, EOF is met. When you enter several lines, EOF is not met, but \n is met. Thus the next getline after the input 5 returns the empty string, the length is 0.
When consuming whitespace-delimited input (e.g. int n; std::cin >> n;) any whitespace that follows, including a newline character, will be left on the input stream. Then when switching to line-oriented input, the first line retrieved with getline will be just that whitespace. In the likely case that this is unwanted behaviour, possible solutions include:
An explicit extraneous initial call to getline
Removing consecutive whitespace with std::cin >> std::ws
Ignoring all leftover characters on the line of input with cin.ignore(std::numeric_limitsstd::streamsize::max(), '\n');
The other line lengths are increased perhaps by the pasting the text containing \r\n that are not processed by the MS specific text file input conversions in the middle.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
My first stackoverflow post!
After entering a value for age into a declared and initialized int,
something weird happens and the value explodes. I test my code and could not see why it happens. After rechecking I can see that it is the last peice of code that did something to my int value.
I ask the stackoverflow gods "Why".
My code here:
int main()
{
cout << "Please enter your name and age\n\n";
string first_name;
int age(0);
cout << age << "\n\n"; // for testing why i get a huge number for age
cin>> first_name >> age;
cout << age << "\n\n"; // for testing why i get a huge number for age
cout << "Hello, " << first_name << " age " << age << '`\n';
keep_window_open(); // window must be closed manually
return 0;
}
This seems to be the offending bit:
'`\n';
This is the output I would get:
Please enter your name and age
0
et
23
23
Hello, et age 2324586
'`\n'
That's actually two characters, not only the newline feed. Plus you use single quotation marks, these are only used for single characters since char literals are of type const char.
The standard says:
The value of an integer character constant containing more than one
character (e.g., 'ab'), or containing a character or escape sequence
that does not map to a single-byte execution character, is
implementation-defined.
And thus the numbers after 23 : 24586 is the implementation-defined part that's causing weird output here. Use double quotes or '\n'.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
In order to substract a timestamp from my string i am using substring( pos,#char).
My code works partially. The problem that i have is consistency.
I am retrieving a string from a textfile in the format "Name Time" ,
Example : "Don 00:12".
this string is extracted from the file into HighScoreInfo1.
Also from a different file i am extracting a string, which is the name part, into previous_name.
With this information i am trying to calculate the position where the substring has to start.
int test = HighScoreInfo1.size() - (previous_name.size()+1 );
i already took measures for the extra char which is a space, thats the +2.
1 for the space and 1 to get to the position where he needs to start.
the timestamp, 00:00, is five characters long.
int test = HighScoreInfo1.size() - (previous_name.size()+2 );
TimeToBeat = HighScoreInfo1.substr(test, 5);
TestFile << "Orginal string size " << ">>" << HighScoreInfo1.size() << " " << "size of name"<< ">>" <<previous_name.size()+2<<" " << "Position "<< test << endl;
TestFile << "Orginal string " << ">>"<<HighScoreInfo1 << " " << "Substring"<< ">>" <<TimeToBeat << endl;
this is my output with a long name:
Orginal string size >>14 size of name>>10 Position >> 4
Orginal string >>Chrystel 00:09 Substring>>stel
Sidenote: you cant see it, but with the above example the space after "stel" is the fifth character.
This is my output with a short name:
Orginal string size >>9 size of name>>5 Position>> 4
Orginal string >>Don 00:09 Substring >>00:09
with the shorter name i get my timestamp perfectly.
How can make this works consistent.
I did not added the rest of my code because that part works. it is basically only the substring part that does not work consistent.
How can i fix this?
You're not calculating test correctly. It should just be 1 more than the size of the name, not the size of HighScoreInfo1 minus that (that's the length of the timestamp, which you know is 5). You only need to add 1, not 2, because positions are zero-based.
int test = previous_name.size() + 1;
DEMO
It only works with the shorter name by coincidence, because the name happens to be 3 characters long.
int test = HighScoreInfo1.size() - (previous_name.size()+2 );
This calculates the length of the time (which is always 5).
TimeToBeat = HighScoreInfo1.substr(test, 5);
This gets the characters 5-10. Always. Regardless of the length of the string. Perhaps you meant to do this, which reads the last five bytes?
TimeToBeat = HighScoreInfo1.substr(HighScoreInfo1.size()-5);
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I've tried this, but I having no luck, I'm am looking to get user input 5 letters and then print them out.
string input = "";
const int max = 5;
char string[max] = { };
cout << "Please enter 5 letters: " << endl;
cin.getline(string, max, '\n');
cout << "Your letters :" << string[max];
I think I figured out what's not working:
First, you are printing out string[max] at the end. Since string is a char[] of size max, it actually has no data at index max--its indices are 0 to max-1. You are actually printing out a random character from whatever happens to be in memory immediately after the characters of your string variable.
So instead of << string[max] in the last line, it should be << string.
Second, after making that change, it will still seem to print only 4 characters, instead of the 5 that were entered. This is because strings in the form of char[]s have a null terminator. So since you are telling cin.getline to only fill up 5 characters in string, it fills the first 4 with actual characters from input, and then the last character is '\0'.
So if the input is "hello", then string will contain the following values: { 'h', 'e', 'l', 'l', '\0' }. And then when you print it, there are, of course, really only 4 characters in the array.
And two notes: string input is not used anywhere in your program, so it should be taken out of the question. And also, you really should call your char string[max] variable something else, to reduce confusion.
I hope this helps!
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
The program is Working perfectly fine .. but in strings if i want to restrict my username to 8 characters what should i do ? ?
cout << "Enter your Username it should have a maximum limit of 8 characters\n " << endl;
getline(cin, user, '\n');
i want here that it should restrict user for 8 characters .. if greater then 8 .. then it should keep asking
user (while loop ??)) until user enters characters less then 8 ..
int mystrcmp(const char *s1, const char *s2)
{
while (*s1==*s2)
{
if(*s1=='\0')
return(0);
s1++;
s2++; }
return 1;//return(*s1-*s2);
}
your int mystrcmp(const char *s1, const char *s2) was returning the difference b/w the ascii values of first non-matched chars in strings s1 and s2 and it isnt always 1 as your code supposed to.
A clean implementation of your code can be found here ideone link
You have a few confusions, notably between C++ strings and C strings.
Your mystrcpy function is an attempt to copy a C style string, but it's not necessary in C++. Here's how you do it in C++. Replace this
mystrcpy(new_user,user)
with this
new_user = user;
As you can see it's a bit easier to copy a C++ string than a C string. You can delete the mystrcpy function.
Similarly your mystrcmp function is an attempt to compare C strings. Again it's not necessary in C++. Replace this
f = mystrcmp(user2,new_user);
if (f==0)
{
cout << "Successful Login!! \n ";
}
with this
if (user2 == new_user)
{
cout << "Successful Login!! \n ";
}
Again you can see that comparing C++ strings is easier than comparing C strings. Again you can delete the mystrcmp function.
There a few other errors, in the logic, and some missing semi-colons, but I'll leave you do figure those out.
Your code is pretty much all over the place. For instance:
You need to #include <string> if you're going to use std::string.
cin >> a; if ( a == 1 ) - what if the user doesn't enter an integer at all? You'll be comparing the value of an uninitialized int to 1, which puts you in undefined behavior land. You should check the return from cin, or at a minimum initialize a.
As John mentioned, you read in std::strings, and then attempt to treat them like C strings. Don't, just use new_user = user and if ( user2 == new_user ).
If the user doesn't "Enter 1 to enter Signup Screen" you take them to the signup screen anyway.
In your mystrcmp() function, you return 0 if *s1 == '\0', but you fail to check if *s2 == '\0'. This means two things - one, if s2 is shorter than s1, then you're going out of bounds and invoking undefined behavior again, and two, if s2 is longer than s1 but begins with s1 (e.g. if s1 contains "billy" and s2 contains "billybob") then your function will say they are equal when they are not.
Also in your mystrcmp() function, this: return(*s1-*s2) will either always return 0 less the value of the element of s2 with the same index as the last index of s1, or it'll invoke undefined behavior if s2 is shorter, as already explained. Either way, it's almost certainly not something you want to return.
mystrcpy(target,source) is not a valid function definition. This function also only copies the first character of source to the first character of target.
When you loop following an incorrect entry, you check if (f == 0) and if (f == 1), but you never set f during this loop, so no matter what the user enters, you'll always just be checking what the initial result was, regardless of what they enter next.