scanf formatted multiple special characters with array [duplicate] - c

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;
}

Related

what is the difference between char and int used in scanf function in a loop? [duplicate]

This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed 11 months ago.
when I write a for loop to scanf some int value, the output is correct.
however, I try to this loop to scanf some char value, it seems something wrong.(I was wondering the space or '\t' as a char to be scanned)
//when the input are
2
1 2
3 4
//
#include<stdio.h>
int main(void){
int n;
scanf("%d", &n);
int x;
int y;
for(int i = 0; i< n; i++){
scanf("%d %d", &x, &y);
}
return 0;
}
//when I enter
2
a b
the program is finished and i cannot enter more char.
//
#include<stdio.h>
int main(void){
int n;
scanf("%d", &n);
char x;
char y;
for(int i = 0; i< n; i++){
scanf("%c %c", &x, &y);
}
return 0;
}
Remember, the space (' ') is also a char, so the scanf is reading the space instead of the second letter.

Can't put Characters in an array of characters in C [duplicate]

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.

Sscanf - parsing with different delimiters

I want parse my string using sscanf:
char string[] = "/home/my/estf 122,323 452,323 662,343";
First element of string it's path and next are ints where comma or white characters are delimiters. This is my full code:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char string[] = "/home/my/estf 122,323 452,323 662,343";
char path[100];
int int1, int2, int3, int4, int5, int6;
sscanf(string, "%s %d[^,] %d %d[^,] %d %d[^,] %d",
path, &int1, &int2, &int3, &int4, &int5, &int6);
printf("Path:%s INT1:%d INT2:%d INT3:%d INT4:%d INT5:%d INT6:%d\n",
path, int1, int2, int3, int4, int5, int6);
return 0;
}
What it's wrong? Is it possible to extend it, to parse dynamic numbers of ints (no 6 exactly) and store it in integer array?
You can do something like this:
char a[3][16], z;
int b[8] = {0};
char x[] = "/home/my/estf 122,323 452,323 662,343", y[64];
sscanf(x, "%c %[^/ ,] %c %[^/] %c %[^/ ] %d %c %d %d %c %d %d %c %d", &z, a[0], &z, a[1], &z, a[2], &b[0], &z, &b[1], &b[2], &z, &b[3], &b[4], &z, &b[5]);
for (int i = 0; i < 3; i++) {
printf("%s ", a[i]);
}
for (int i = 0; b[i] != 0; i++) {
printf("%d ", b[i]);
}
There may be better methods to do this, but using sscanf you have do this way. You may even convert the really long sscanf line into a loop.
When using sscanf, you must consume the characters you're specifying in the negated scanset. So in case of a scanset like this: [^/] will read all the characters upto the first occurence of /. But, pointer will be still at the / in the source string. You must consume that / and continue reading ahead.
for more information on how sscanf works, look at man sscanf
It seems you want to be using something like strtok()
Here is this example slightly modified:
/* strtok example */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main ()
{
char string[] = "/home/my/estf 122,323 452,323 662,343";
char * pch;
pch = strtok (string, " ,");
while (pch != NULL)
{
pch = strtok (NULL, " ,");
if (pch)
{
int val = atoi(pch);
printf ("%d\n", val);
}
}
return 0;
}
Is it possible to extend it, to parse dynamic numbers of ints (no 6
exactly) and store it in integer array?
You can use strtol in a loop:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char str[] = "/home/my/estf 122,323 452,323 662,343";
char path[100];
int ai[32];
char *ptr;
int n = 0;
ptr = strchr(str, ' ');
sprintf(path, "%.*s", ptr - str, str);
while (*ptr) {
ai[n++] = (int)strtol(ptr, &ptr, 10);
if (*ptr) ptr++;
}
printf("Path:%s", path);
for (int i = 0; i < n; i++) {
printf(" INT%d=%d", i + 1, ai[i]);
}
printf("\n");
return 0;
}

My string compare is coming out wrong

hi my program is to enter a number which gives the length of the string then the string and then finally a letter which should then tell me how many times that letter is in the string. Currently to help me figure out what is wrong with my code i can see that the strcmp is resulting in the same ascii number but negative. eg for the letter a the number is 97 but the strcmp is giving out -97 so the strcmo doesnt show the character as being in the string and results in the incorrect result. Any help would be greatly appreciated. thanks
#include
#include
int main(void)
{
char myChar[100], z, k;
int counter, n, g=0, r, i, l;
counter=0;
scanf("%d",&n);
while (counter<n)
{
counter++;
scanf(" %c",&myChar[counter]);
}
scanf(" %s", &z);
for(i=0;i<n+1;++i)
{
k=myChar[i];
r=strcmp(&z, &k);
l=r;
//printf("\n%c", myChar[i]);
printf("%d\n", l);
if(r==0)
{
g++;
printf("%d\n", g);
}
}
printf("\n\n%d\n", g);
return (0);
}
#include <stdio.h>
#include <string.h>
int main(void){
char myChar[100], str[64];//
int counter, n;
int i, j, k;
printf("number of charactors : ");
scanf("%d",&n);
for (i=0; i<n; ++i){
scanf(" %c", &myChar[i]);
}
printf("input string : ");
scanf("%63s", str);//"%s" : The useless one letter to input as a string. "%c" for &z
for(i=0;i<n;++i){
counter = 0;
for(j=0;str[j]!='\0'; ++j){
k = (str[j] == myChar[i]);//Comparison of each character
counter += k;//if(str[j] == myChar[i]) ++counter;
}
printf("%c is %d\n", myChar[i], counter);
}
return (0);
}

Count all character occurrences in a text file

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.

Resources