How to put the string entered into a character array in C++? - c++

Now, I am facing with such a problem: Compare two strings without using "strcmp" in library function.
I have defined the function "mystrcmp" correctly, but I also have to put the string entered into a character array. How can I realize it?
Here is my wrong codes:
char a1[100],a2[100];
int j=0;
do
{
cin>>a1[j];
j=j+1;
}while(getchar()!=10);
int k=0;
do
{
cin>>a2[k];
k=k+1;
}while(getchar()!=10);
cout<<j<<" "<<k<<"\n";
I want to see if the loops are correct through j and k. Unfortunately, the results are wrong.
For example, when I enter "abcdefg" and "gfedcba", I get the result "j=4, k=4".
What's wrong with my codes? How can I correct it?
I'm looking forward to your answers. Thank you.

Why are you using the value 10 in your code? Don't use integer literals in place of character constants, because when you attempt to run this code on a computer that uses the EBCDIC character set you'll notice that '\n' has the value 37, not 10. Use '\n' instead of 10.
Don't mix getchar and cin code. That's a pretty bad idea, because they both consume one character each. In other words, getchar() is consuming one byte, and cin is consuming one byte, so you're consuming two bytes per loop and only storing one of those bytes. If you're going to use getchar, I think you mean something like this:
for (int c = getchar(); c >= 0 && c != '\n'; c = getchar()) {
a1[j++] = c;
}
a1[j] = '\0';
The same sort of thing using C++'s cin:
for (int c = cin.get(); cin.good() && c != '\n'; c = cin.get()) {
a1[j++] = c;
}
a1[j] = '\0';

This is dangerous code. You can write out of a1 & a2 bounds. Use functions made for this, for example cin.getline
http://www.cplusplus.com/reference/istream/istream/getline/

Related

Char array gets cleared after function gets() on C++

I'm trying to learn C++. Sometimes I get confused by C style strings and its functions. I've been using
char var[1];
fflush(stdin);
gets(var);
to write a string into a char array. I don't know if thats the most efficient way but thats how I've been taught.
Now, I'm making a console program in which I read some variables that way and make things with them. It's all working fine but I have a char array, estudios[1] and I have to compare it with strcmp (I'm not talking about the strcmp(estudios, "N") != 0 I wrote below) to a specific value and i found that te result of the comparation was always the same no matter the value estudios had. I realized that after this chunk of code:
if (strcmp(estudios, "N") != 0){
cout << "Estudios completos o incompletos?" << endl;
fflush(stdin);
gets(indicador);
}
Let's say that the value of estudios is "P". Before the code i showed the value of estudios is "P" but after it it changes it value to "". To be more precise it changes after the gets(indicator);
Why does that happen? Is it supposed to do that? Sorry for such a newbie question
Don't use gets. It is dangerous. It shouldn't be used at all. It has been removed from both C and C++ standards. Don't use gets.
I have a char array, estudios[1]
strcmp(estudios, "N") != 0
A character array of length 1 can only contain the null terminated string of length 0. The string "N" contains two characters: 'N' and '\0' which is the null termination character.
If estudios[0] is anything other than the null termination character, then it doesn't contain a null terminated string, and passing it to strcmp will violate the pre-conditions of the function and the behaviour of the program will be undefined.
Why does that happen?
The behaviour of the program is undefined.
Is it supposed to do that?
You aren't supposed to pass non-null-terminated strings into strcmp.
Here is a fixed program that probably does what you're trying to do (your example is incomplete, so I'm guessing):
std::string indicator;
char c;
std::cin >> c;
if (c != 'N') {
cout << "Estudios completos o incompletos?" << endl;
std::cin >> indicador;
}

Why does getline behave weirdly after 3 newlines?

I'll preface this by saying I'm relatively new to posting questions, as well as C++ in general, my title is a little lame as it doesn't really specifically address the problem I am dealing with, however I couldn't really think of another way to word it, so any suggestions on improving the title is appreciated.
I am working on a relatively simple function which is supposed to get a string using getline, and read the spaces and/or newlines in the string so that it can output how many words have been entered. After reaching the character 'q' it's basically supposed to stop reading in characters.
void ReadStdIn2() {
std::string userInput;
const char *inputArray = userInput.c_str();
int count = 0;
getline(std::cin, userInput, 'q');
for (int i = 0; i < strlen(inputArray); i++){
if ((inputArray[i] == ' ') || (inputArray[i] == '\n')){
count += 1;
}
}
std::cout << count << std::endl;
}
I want to be able to enter multiple words, followed by newlines, and have the function accurately display my number of words. I can't figure out why but for some reason after entering 3 newlines my count goes right back to 0.
For example, if I enter:
hello
jim
tim
q
the function works just fine, and returns 3 just like I expect it to. But if I enter
hello
jim
tim
bill
q
the count goes right to 0. I'm assuming this has something to do with my if statement but I'm really lost as to what is wrong, especially since it works fine up until the 3rd newline. Any help is appreciated
The behaviour of the program is undefined. Reading input into std::string potentially causes its capacity to increase. This causes pointers into the string to become invalid. Pointers such as inputArray. You then later attempt to read through the invalid pointer.
P.S. calculating the length of the string with std::strlen in every iteration of the loop is not a good idea. It is possible to get the size without calculation by using userInput.size().
To fix both issues, simply don't use inputArray. You don't need it:
for (int i = 0; i < userInput.size(); i++){
if ((userInput[i] == ' ') || (userInput[i] == '\n')){
...

Trying to read a single character at a time into an array of indefinite size

I am a CS student working on a c++ project. We have been instructed to declare a struct and use it to read in an array of chars and keep a tally of how many letters are used in the string. We are not allowed to use a string; it MUST be an array of our declared struct.
The input must be as long as the user wants; the code has to be able to accept new lines of input and be terminated by '.'
I'm really struggling here. I don't even know where to begin. I've thrown together some code as best-guess for what to do, but it crashes after pressing "." then enter, and I don't know why.
//declare struct
struct data
{
int tally = 0;
char letter;
};
//size of string to read in at a time
const int SIZE_OF_CHUNK = 11;
int main()
{
//input chunk of struct
data input[SIZE_OF_CHUNK];
int placemark,
length;
cout << "Enter sequence of characters, '.' to terminate:" << endl;
do
{
for (int index = 0; (input[index].letter != '\0') && (input[index - 1].letter != '.'); index++)
{
cin >> input[index].letter;
placemark++;
}
//I intend to put something here to handle if the code
needs to read in another chunk, but I want to fix the crashing
problem first
}
while (input[placemark].letter != '.');
//print out what was read in, just to check
for (int index = 0; input[index].letter != '\0'; index++)
{
cout << input[index].letter;
}
return 0;
}
I've tried looking up how to read in a single character but haven't found anything helpful to my circumstances so far. Any tips on what I'm doing wrong, or where I can find helpful resources, would be very much appreciated.
Are you sure you must use a declared struct?
If you just want to count the number of times a character has appeared, you don't need to store the character; you just need to store the number of times it appeared. So just unsigned lettersCount[26], and each index maps to a letter (i.e. index 0 means a, index 1 means b). Whenever a letter appears, just increase the count of that index.
You can map a letter to the index by making use of ASCII. Every letter is represented by a decimal number that you can look it up at ASCII table. For example, the letter a is represented by the decimal value 97, b is 98 and so on. The number increases successively, which we can make use of. So if you want to map a letter to an index, all you need to do is just value - 97 or value - 'a'. For example, if you read in the letter a, take away 97 from that and you'll get 0, which is what you want. After getting the index, it's just a simple ++ to increment the count of that letter.
Regarding the treatment of uppercase and lowercase (i.e. treat them the same or differently), it'll be up to you to figure it out how to do it (which should be fairly simple if you can understand what I've explained).

using getchar() and getting stuck in loop [duplicate]

For my homework assignment, I need to implement Horners Algorithm for converting between bases.
I have been told to use getchar() for this assignment. But I am having a problem where when I hit enter, the program doesn't terminate and just takes in more chars.
Example:
bryce> ./pa1
Enter the fromRadix:16
Enter the toRadix:2
abc
abc
^C
bryce>
Code:
int readRadixA(int radixA)
{
char myChar = getchar();
int result = 0;
int run = 0;
while(myChar != EOF)
{
if(myChar == "\n")
break;
Horners();
myChar = getchar();
}
return result;
}
I am not asking for help implementing Horners; I am asking for help to terminate the getchar() correctly.
if(myChar=="\n")
^ ^
You're comparing myChar wrong. Try this instead:
if(myChar == '\n')
^ ^
A second problem is that getchar returns int, not char. Maybe you can rewrite it like this:
int myChar;
while((myChar = getchar()) != EOF && myChar != '\n')
{
/* Your stuff. */
}
EDIT
In light of comments, I think some stdio operation before that while is leaving a \n in the buffer.
Instead of scanf("%d", &radix) try:
scanf("%d ", &radix);
^
That space will make scanf eat the remaining blanks (including the newline).
Check the return type of getchar(). Yes, it's an int. That's because EOF must have a value that can be distinguished from a valid character. myChar must actually be made to be int.
Try this code
int readRadixA(int radixA)
{
char myChar;
int result = 0;
int run = 0;
do
{
myChar = getchar();
// implement horners here
}while(myChar != 13);
return result;
}
I checked your code I think you are leaving a '\n' in the input keyboard buffer after the toRadix.
And their is one more thing that
getchar()
reads all the characters in one go till a '\n' is received.
And there is one more mistake you have committed by comparing a
char to a pointer e.g mychar=="\n"
further information about your implementation of toRadix can be really helpful to answer your question
On linux, to end the standard input, you have to type  Ctrl-D. The kernel and tty layers makes that an end-of-file mark or condition. Then getchar gives EOF (which is not a valid char, for example on systems where char are unsigned bytes between 0 and 255, EOF could be -1).
Notice that feof(3) is valid only after a read operation (e.g. getchar, fgets, etc...) so coding while(feof(stdin)) is generally wrong (contrarily to what I wrote in the previous version of this answer). You'll better test that getchar is returning EOF so your myChar should be an int (not a char).

Entering a string of characters using arrays and pointers

Ok guys, i'm very beginner and trying to enter string to a char array using pointers..and then display what i've written.
There're two things i want to ask about. First , if i didn't want to specify a size for the array and just want it to expand to contain all string i've entered ..how is that ?
And second after i enter the string and display it...it won't contain the SPACE between word...
like if i entered "i love cookies"...it will be displayed as "ilovecookies"..So how to solve that ?
Here's my little code ...
#include <iostream>
using namespace std;
int main()
{
char *strP , str[100] ;
strP = str ;
for(int i =0 ; i<10 ; i++) cin >> *(strP+i) ;
for(int i =0 ; i<10 ; i++) cout << *(strP+i) ;
return 0;
}
sorry for my silly questions, I'm beginner to this language as said and don't want to miss things before moving on .
Thanks in advance .
1) You need to either use a string object or new if you want to dynamically resize your string.
2) It doesn't contain the spaces because cin reads one words at a time. There are several ways to get around this. The one I would use is switch to using scanf and printf instead of cin and cout. Or, as vivin said, you can use getchar()
EDIT: grammar
cin always stops when it encounters a space. If you're entering character by character, try using getchar().
Arrays can't change their size. You should use std::vector<char>, or even better for strings you would use std::string.