This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed 4 years ago.
I'd like to create and manipulate an array of caracters. I don't want to use strings.
here is my code in C language :
int main(int argc, char *argv[]) {
char s[4];
int i;
for(i = 0; i < 4; i++){
printf("Character at %d : ",i);
scanf("%c",&s[i]);
printf("%c",s[i]);
}
return 0;
}
When I execute it, it seems that :
The compiler jumps from an element at i in the array to the element at i+2
Nothing is added in the array. the array stays empty
I'd like to understand what's wrong with the scanf("%c",&s[i]); that I think it is that instruction wich causes the problems in this code.
scanf() doesn't work as you expected. scanf() also considers the enter that you press as a character. If you are adamant about using scanf(), here are a couple of workaround for your current code.
Method 1
int main(int argc, char *argv[]) {
char s[4];
char enter;
int i;
for(i = 0; i < 4; i++) {
printf("Character at %d : ",i);
scanf("%c", &s[i]);
scanf("%c", &enter);
printf("%c \n", s[i]);
}
return 0;
}
Method 2
Use the same code, but enter all the four character at once.
int main(int argc, char *argv[]) {
char s[4];
int i;
for(i = 0; i < 4; i++) {
printf("Character at %d : ",i);
scanf("%c", &s[i]);
}
for(i = 0; i < 4; i++) {
printf("\n %c", s[i]);
}
return 0;
}
Output looks like:
Character at 0 : abcd
Character at 1 : Character at 2 : Character at 3 :
a
b
c
d
Method 3
As mentioned by Xing in comments, this looks better way to achieve it. But make sure you note the whitespace added before %c in scanf().
int main(int argc, char *argv[]) {
char s[4];
int i;
for(i = 0; i < 4; i++) {
printf("Character at %d : ",i);
scanf(" %c", &s[i]); // Note the whitespace before %c
printf("\n %c", s[i]);
}
return 0;
}
It doesn't work as you expected because scanf() takes only one character but it will only do that until you pressed enter. So the enter character is still in the buffer and to be read by the next iteration of scanf().
See How to clear input buffer in C? for suggestions on how to change the code.
Related
This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed 4 years ago.
I want to have 3 inputs of symbols e.g. | or %, but instead of getting | | %, I got | |.
Terminal:
| ^ !
| ^
The code is here:
#include <stdio.h>
char a[10], b[10], c[10];
int i;
int count;
int main(int argc, char const *argv[]) {
scanf("%d", &count);
for (i = 0; i < count; i++) {
scanf("%c %c %c", &a[i], &b[i], &c[i]);
printf("%c %c %c\n", a[i], b[i], c[i]);
}
return 0;
}
Please tell me what am I doing wrong. Thanks.
To read single characters symbols optionally separated by whitespaces, you must explicitly ignore this whitespace with a in the format string before the %c.
Also check the return value of scanf().
Here is a corrected version:
#include <stdio.h>
int main(int argc, char const *argv[]) {
char a[10], b[10], c[10];
int i, count;
if (scanf("%d", &count) == 1 && count <= 10) {
for (i = 0; i < count; i++) {
if (scanf(" %c %c %c", &a[i], &b[i], &c[i]) != 3)
break;
printf("%c %c %c\n", a[i], b[i], c[i]);
}
}
return 0;
}
I am trying to display and print a word from the user and store it into my array which is called
char word[20]
But I am having trouble. I know we use a "for loop" to scan it into the array but I keep going in circles and I believe the problem is with the i < 20.
I researched this and found that the answers to this are extremely experienced and I need a really basic way of doing it without the extra stuff. So all I want is to get word from the user, store it and print it onto the screen.
Can someone help without experienced code?
Code in C
char getWord(char word[]);
int main()
{
char word[20];
getWord(word);
return 0;
}
char getWord(char word[])
{
int i;
printf("Enter a word: ");
for (i = 0; i < 20; i++)
{
scanf(" %c", &word[i]);
}
return word;
}
All you want is
#include <stdio.h>
int main() {
char word[20];
scanf("%s", word); // Read and store
printf("%s\n", word); // Print
return 0;
}
You can use fgets and puts to read and write a string.
#include<stdio.h>
#define MAX 20
int main()
{
int ar[MAX], i, count;
fgets(ar, MAX, stdin); //it will accept whitespaces as well
puts(ar); //displaying entered string
return;
}
if you want to read via characters, ending character should be set to null character for it to be string.
char getWord(char word[]);
int main()
{
char word[20]
getWord(word);
printf("%s\n", word);
return 0;
}
char getWord(char word[])
{
int i;
char c;
printf("Enter a word: ");
for (i = 0; i < 19; i++)
{
scanf("%c", &c);
if ( c == '\n' )
break;
word[i]=c;
}
word[i]='\0';
return word;
}
Actually recently i found a problem where i need to count occurrence a given(by oj) char in a given string(with test case).So i write this code but output is not as i desired.I'm a beginner so i'll be greatly thankful for any kind of instructive advice or help.THANK YOU.
#include<stdio.h>
#include<string.h>
int main ()
{
int ara [123];
char s[1000];
int l, j, i, len;
char c;
scanf ("%d\n", &l);
while (l >= 0){
for (i = 65; i <= 122; i++)
{
ara[i] = 0;
}
fgets(s, 1000, stdin);
len = strlen(s);
for (i = 0;i <= len; i++)
{
ara[s[i]]++;
}
scanf(" %c\n", &c);
j = c;
printf("count : %d\n", ara[j]);
l--;
}
return 0;
}
The problem is that scanf is leaving a newline in the input to be read as the target sentence.
You can get around this by using fgets and sscanf instead. I also added some cues to make it easier to know what is expected.
#include <stdio.h>
#include <string.h>
int main (void)
{
int ara [128]; // increased array size
char s[1000];
char t[10];
int l, j, i, len;
char c;
printf("Enter how many loops:\n");
fgets(t, sizeof t, stdin); // replace scanf
sscanf (t, "%d\n", &l); // with sscanf
while (l > 0){ // changed end test
for (i = 'A'; i <= 'z'; i++) // replaced magic numbers
{
ara[i] = 0;
}
printf("Enter the string:\n");
fgets(s, sizeof s, stdin);
len = strlen(s);
for (i = 0;i <= len; i++)
{
ara[s[i]]++;
}
printf("Enter the letter:\n");
fgets(t, sizeof t, stdin); // replace scanf
sscanf (t, "%c\n", &c); // with sscanf
j = c;
printf("count : %d\n", ara[j]);
l--;
}
return 0;
}
Program session
Enter how many loops:
2
Enter the string:
one two three four
Enter the letter:
o
count : 3
Enter the string:
three seven
Enter the letter:
e
count : 4
Note that ideally, you should also check the function return values from fgets and sscanf.
The following code snippet is intended to count all the symbols met in a file after text is entered, next step is counting the occurrences of all characters (For instance 'a' met 3 times, 'b' 0 times etc.). However when I compile the loop goes infinite and the counting is always 0. My question is if it could be fixed or rewritten in another way.
char type, c, text[100]; counts[100];
int count=0, i;
while((type=getchar())!=EOF) {
fputc(type, f); count++;
}
printf("Symbols found: %d", count-1);
rewind(f);
while(fscanf(f, "%s", &text)) {
for (i = 0; i < strlen(text); i++) {
counts[(text[i])]++;
printf("The %d. character has %d occurrences.\n", i, counts[i]);
}
}
You can build your histogram as you read the input. The return value from getchar() is an int, not a char, since it has to represent EOF in addition to the 256 char values. Once the histogram has been built, you can iterate over the buckets and print them. Here, I have assumed that all 256 char values are possible, and included code to display unprintable characters in hex notation.
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main(int argc, char **argv)
{
int c;
int i;
int histogram[256];
int total;
memset(histogram, 0, sizeof(histogram));
total = 0;
while ((c = getchar()) != EOF) {
histogram[c]++;
total++;
}
printf("Symbols found: %d\n", total);
for (i = 0; i < 256; i++) {
if (histogram[i]) {
char repr[5];
sprintf(repr, isprint(i) ? "%c" : "\\x%02x", i);
printf("The '%s'. character has %d occurrences.\n", repr, histogram[i]);
}
}
return 0;
}
Your for loop scans the string with variable i being an index to the character tested, but your printf says i is a symbol accounted.
You should separate counting and printing results:
char * ptr;
while(fscanf(f, "%s", text))
for (ptr = text; * ptr != 0; ptr++)
counts[ (unsigned char)*ptr ]++;
for( i = 0; i < 256; i++)
printf("The %d. character has %d occurrences.\n", i, counts[i]);
Don't forget to declare count[ 256] and note that scanf gets text, not `&text~as a destination.
int main(int argc, char const *argv[])
{
char str[100][100];
int n, i;
scanf("%d", &n);
for (i = 0; i < n; i++)
gets(str[i]);
for (i = 0; i < n; i++)
printf("%s\n",str[i]);
}
Why i'm unable to read the string properly?
raja#raja-Inspiron-N5110:~/myctry$ ./a.out
2
abc def
abc def
change
scanf("%d",&n);
to
scanf("%d\n",&n);
if you press enter to input your number. this form gets rid of the '\n' in str[1] when scanf().
You're using 1-based indexing. C uses 0-based indexing.
Change the for loop to for(i=0;i<n;i++)
Never use gets(). Because it is impossible to tell without knowing the data in advance how many characters gets() will read, and because gets() will continue to store characters past the end of the buffer, it is extremely dangerous to use. It has been used to break computer security. Use fgets() instead.
MAN
There are several issues:
You need to start your for loop at index 0.
You should print your string out
int main(int argc, char const *argv[])
{
char str[100][100];
int n,i;
scanf("%d",&n);
for(i=0;i<n;i++) // start at i = 0
gets(str[i]); // store string to str[0]
printf("%s\n", str[0]); // print the results
}
Start loop from index 0 - you have started from 1
for (i = 0; i <= n; i++)
Moreover, you should print the string as well.
#include<string.h>
#include<stdio.h>
int main()
{
int n,i;
char str[100][100];
scanf("%d", &n);
for(i=0;i<n;i++)
{gets(str[i]);}
for(i=0;i<n;i++)
{printf("%s\n",str[i]); }
return 0;
}
As 7-isnotbad said,gets() is not safe,fgets() is a better choice.
Both gets() and fgets() read a line end by '\n' from buffer.
maybe you can try this code:
#include "stdio.h"
#define MAX_LINE 1024
#define MAX_ROW 100
int main()
{
char str[MAX_ROW][MAX_LINE];
int i,n;
printf("input the row of lines :\n");
scanf("%d\n",&n);
if(n < 1)
{printf("input error!\n");return -1;}
for(i = 0; i < n; ++i)
fgets(str[i],MAX_LINE - 1,stdin);
for(i = 0; i < n; ++i)
fputs(str[i],stdout);
return 0;
}