problems converting character array to string array - c

Hi i am quite new into programming and i need some small help on converting char array to string and i am not sure where has gone wrong. i need to get user input in %c and i input for the first input - aabcc and then clicks on enter
the second input - fsdff then enter again
3rd input - rewrr then enter again
4th input - zzxcc and enter again the
last input - asdfg.
But the outputs gives me array 1 = aabcc , 2nd array = fsdf (one of gone missing) 3rd array = f '\n' ... followed by 3rd 4th and 5th array displayed incorrectly. Thanks all in advanced.
int main()
{
int i, j;
char ch[5][6];
char c[5][5];
for (i = 0; i < 5; i++)
for (j = 0; j<5; j++)
scanf("%c", &c[i][j]); // get user input
memcpy(ch[0], c[0], 5);
ch[0][5] = '\0';
memcpy(ch[1], c[1], 5);
ch[1][5] = '\0';
memcpy(ch[2], c[2], 5);
ch[2][5] = '\0';
memcpy(ch[3], c[3], 5);
ch[3][5] = '\0';
memcpy(ch[4], c[4], 5);
ch[4][5] = '\0';
printf("array 1 = %s, array 2 = %s , array 3 = %s , array 4 = %s , array 5 = %s ", ch[0], ch[1], ch[2], ch[3], ch[4]);
}

Change below scanf
scanf("%c", &c[i][j]);
to
scanf(" %c", &c[i][j]);
^
|
space here
Reason behind it is, you are entering input as aabcc<Enter>, there are 6 characters in the input buffer. scanf("%c") reads the a, a, b, c and then c, interpreting them as the aabcc, but the newline character is still in the input buffer. Thats why you see newline as well when you try printing them.

Your scanf buffer (c[][]) is too small to hold all the characters from a single entry. As another writer pointed out, you have not added space for the '\n' character in your static allocation.
The size of your scanf character array (c[][]) should be = max no. of words x (max no. of chars in a word + 1)
The plus one is for the newline character.
#define MAXWORDSIZE 5
#define MAXWORDS 10
char c[MAXWORDS][MAXWORDSIZE + 1]; // Newline character
char ch[MAXWORDS][MAXWORDSIZE + 1 + 1]; // Newline and NUL character

Related

How to convert every letter of a string to another letter? in C

This is my first post, tell me if the format is not approppiate. Thanks.
I'm currently trying to design an algorithm that doing such thing:
It asks for different letters to make a string of n digits, then it asks for a key letter 'cypher key', and then it converts every letter of the string adding the key letter, for example:
How many characters? 3
Next character (1/3)? h
Next character (2/3)? a
Next character (3/3)? l
-> [ h a l ]
Caesar cypher key? b
Encrypting...
-> [ i b m ]
Here I leave another example of what the code should do:
How many characters? 3
Next character (1/3)? z
Next character (2/3)? h
Next character (3/3)? h
-> [ z h h ]
Caesar cypher key? a
Encrypting...
-> [ z h h ]
In this example, as a=0, the letters will be the same ones
As you can se it asks for an amount of characters, that will be the size of the string, then you can input the numbers, then it prints the numbers, then it asks for the key letter, it "encrypts" the string, and then it shows the same string but with the value of the key letter added to each one of the letters of the string.
Obviously to make that possible ASCII table has to be used.
I'm not very good at using strings and functions, so I may have caused some errors.
Here I leave the code with comments (//...) I made for you to see:
#include <stdio.h>
#include <string.h>
#define SIZE 20
//argument with no return value function to change the value of str1 with the 'cypher key'.
void moveLetters (char str1[], char cypher_key) {
int i;
int len;
len = strlen(str1);
//loop to convert every character of the string with the cypher key value
for (i = 0; i < len; i++) {
str1[i] = (str1[i] + cypher_key - 97 * 2) % 26 + 97;
}
}
int main () {
int n_characters;
char str1[SIZE];
char cypher_key;
int i;
int t = 0;
//asks for the amount of values of the string which can't be less than 0.
do {
printf ("How many characters? ");
scanf ("%d", &n_characters);
} while (n_characters <= 0);
//asks for every character depending on the amount.
for (i = n_characters; i > 0; i--) {
printf ("Next character (%d/%d)? ", t + 1, n_characters);
scanf ("%s", &str1[t]);
t++;
}
printf ("-> [%s]\n", str1);
printf ("Caesar cypher key? ");
scanf ("%s", &cypher_key);
//here I have my doubts because i don't really know if this is a correct way to send a value to a
//function and return it to the main
moveLetters (str1, cypher_key);
printf ("Encrypting...\n");
printf ("-> [%s]", str1);
return 0;
}
What happens is that for some reason it prints nothing in the last printf, so i don't understand what happens in the void function or somewhere else.
The last printf works. There is no problem at all.Put a new line so you can see it better.
printf ("-> [%s]\n", str1);

My Unknown Numbers of Input Code Duplicates the Last Input

I'm working on one of my C assignments. I have a little problem with taking unknown numbers of input. This is my code:
while ((a = getchar()) != EOF){
ungetc(a,stdin);
scanf(" %c %d %d %d",&a,&b,&c,&d);
arr1[3*i] = b;
arr1[3*i+1] = c;
arr1[3*i+2] = d;
i++;
(I have done all the declaretions befor this)
What i'm trying to do this here is I take inputs and stroe them in three arrays. My input is:
X 10 18 3
r -3 2 1
Y 0 -2 -1
After i write these in terminal, i have to push the buttons ctrl+d twice. And then when i try to check arr1, its like {10, 18, 3, -3 ,2 ,1 ,0 ,-2 ,-1 ,0 ,-2 ,-1} The last input is duplicated and i don't know the reason..
!!! The main thing is that I don't that how many inputs i will take. !!!
Thank you for your help.
After each scanf, the file pointer is left on the trailing newline of input. After the last line of input is scanned and values are assigned to b, c, and d, the getchar in the while loop reads the final newline. Then scanf reads no values so b, c, and d are unchanged. The values that were left from the previous loop are assigned to the array, i is incremented, and then getchar returns EOF and the loop breaks. Always check the value returned by scanf. In other words, this problem evaporates if you use the usual idiom
while(scanf(" %c%d%d%d",&a,&b,&c,&d) == 4) { ...
Also, in this case, the error would have been noticed more readily if you weren't copying the data unnecessarily to the temporary variables b, c, and d, but just did:
while( scanf(" %c%d%d%d", &a, arr + 3*i, arr + 3*i +1, arr + 3*i + 2) == 4
which would be written a lot more cleanly as:
int *base = arr;
while( scanf(" %c%d%d%d", &a, base, base + 1, base + 2) == 4 ) {
base += 3; ...
Note that in all of these, a must really be declared as a char, but to assign a from getchar requires that a be an int, and that should be a clue that trying to use getchar/ungetc is a mistake.
To summarize, on all but the first line of input, getchar is reading '\n', ungetc pushes that newline back to the buffer, and then scanf skips over it because of the leading whitespace in the format string.
regarding:
while ((a = getchar()) != EOF){
ungetc(a,stdin);
scanf(" %c %d %d %d",&a,&b,&c,&d);
arr1[3*i] = b;
arr1[3*i+1] = c;
arr1[3*i+2] = d;
i++;
Suggest using the returned value from scanf(), similar to:
int i = 0;
while ( scanf(" %c %d %d %d",&a,&b,&c,&d) == 4 )
{
arr1[3*i] = b;
arr1[3*i+1] = c;
arr1[3*i+2] = d;
i++;
}

'\n' saved in array after memset (C)

I read chars until '\n', convert them to int and sum the numbers until the result is only one digit.
I can't use mod or .
The first run went well, but the second one keep running and not waiting to \n.
any reason for keeping the '\n'?
#include<stdio.h>
int main(){
char str[8], conv_str[8],c;
int i,val,ans = 0;
while(1){
printf("Enter 8 values(0-9) :\n");
scanf("%[^\n]", str); // Scan values to str untill \n
for(i = 0;i < 8;i++){
val = str[i]-48; //convert from asci to int
ans += val;
}
while(ans > 9){
// itoa convert int to string, str(the input) is the buffer and 10 is the base
itoa(ans,conv_str,10);
ans = (conv_str[0]-48) + (conv_str[1]-48) ;
}
printf("the digit is: %d", ans);
printf("\ncontinue? (y/n)\n");
scanf("%s", &c);
if (c == 'n')
break;
memset(str, 0, sizeof(str));
}
return 0;
}
TIA
You have multiple problems in the code. Some of them are
scanf("%s", &c); is wrong. c is a char, you must use %c conversion specifier for that.
You never checked for the return value of scanf() calls to ensure success.
While scanning for character input, you did not clear the buffer of any existing inputs. Any existing character, including a newline ('\n') already present in the buffer will be considered as a valid input for %c. You need to clear the buffer before you read a character input.

How to write '\n' from keyboard with scanf() in C

I'm new to C and I would like to know if it's possible to write into a string the character \n from the keyboard by using scanf() function.
The code that I'm using is this: (sorry for the Italian variables words)
void riempi_array_stringhe (char* stringhe[], int lunghezza_array)
{
for (int i = 0; i < lunghezza_array; i++) {
stringhe[i] = (char*) malloc(sizeof(char) * 100);
printf("Insert a new string: ");
scanf("%s", stringhe[i]);
}
}
I tried type shift + enter, alt + enter, or to insert \n as input but not works at all.
Thanks in advance!
There is a [ specifier. Quote from scanf(2)
[ — Matches a nonempty sequence of characters from the specified set of accepted characters; the next pointer must be a pointer to char, and there must be enough room for all the characters in the string, plus a terminating null byte.
Example:
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *str[10];
for (int i = 0; i < 10; i++) {
str[i] = (char *)malloc(sizeof(char) * 100);
printf("Insert a new string: ");
scanf("%[^~]", str[i]);
printf("Your input: %s\n", str[i]);
}
return 0;
}
To end the input we should input ~ and then Enter or press Ctrl+D (EOF). We can specify other characters to terminate the input. For example, scanf("%[^X]", str[i]); will terminate the input after user inserts an X and then Enter.
Please note, to prevent your buffer overrun, you should always specify the width of the sequence equals to the buffer size minus one (for NUL character), i.e.:
scanf("%99[^~]", str[i]); // read no more than 99 symbols + NUL

Code doesn't read the last character of string of Characters (C language)

#include "stdio.h"
int main() {
char input[10];
char standart;
int i;
int b = 0;
scanf("%c", &standart);
for(i = 0; i < 10; i++){
scanf("%c ", &input[i]);
if(input[i] == standart){
b++;
}
}
printf("%d", b);
return 0;
}
// ( 2 % a b ( r ) ? ( (
The code is suppost to read the first character in the list, then see how many of said characters there are (not including itself). But the code doesn't read the last character, in short when I input the sample input the code only sees 2 '(' while it should see 3.
You have to do it like this scanf(" %c",&c);
Because it reads '\n' from previous input, so the space will skip the '\n'
For the given input ( 2 % a b ( r ) ? ( (, the program takes the first character ( as input to variable standart -
scanf("%c", &standart);
The problem is occurring because in the first iteration of for loop the scanf was reading the first whitespace character (a blank space) from given input that exists after ( and storing it into input[0].
The for loop runs for 10 iterations and the last character ( is not inserted in the input array because of which the standart character count in input array is coming one less than expected i.e. 2.
Change the for loop scanf statement to -
scanf(" %c", &input[i]); //Removed the space after %c and added a space before %c.
With this, the for loop scanf will eat whitespaces characters.
So, the next character from input - 2 will be stored to input[0] and % will be stored to input[1] and so on and the last character '(' will be stored to input[9].
And the b will have the correct standart character count in input array i.e. 3.

Resources