For my task I have to print numbers to the screen and decode them into their specific letters. I'm using only the letters a-l in this code just to keep it simple so I can understand it.
The problem I'm having is that when I, for example, put in the number 0 which corresponds to the first entry to the array which is a, it will take out a and print b-l.
How do I make it so if I put in the number 0, the code will print only a to the screen?
#include <stdio.h>
int main()
{
char code[] = "abcdefghijkl";
int i, j, k;
printf("how many letters does your code contain?: ");
scanf("%d", &j);
for(i=0; i<j; ++i){
printf("enter a number between 0 and 11\n");
scanf("%d", &k);
printf("%s\n", &code[k]);
}
}
You print only the character at that location, so change
printf("%s\n", &code[k]);
to
printf("%c\n", code[k]);
You should also check that the value you read into k is >= 0 && < 11 , otherwise you'll access the array outside its bounds.
%s format specifier is used for printing strings, you need to use %c specifier which prints a character to the screen.
printf("%c\n", code[k]); instead of printf("%s\n", &code[k]);
Related
I'm trying to make a simple voucher. So, I used a multidimensional string. But facing trouble including space in those strings. Instead, I took words as input. But is there any way to include space? My code is given below-
#include<stdio.h>
#include<string.h>
int main(){
int sum =0, n, i;
puts("Please input how many transactions you want to enlist: ");
scanf("%d", &n);
char list[301][51];
int amount[301];
puts("Please enter the name of your transaction and the amount: (Press space or enter to toggle between name and amount . And avoid using spaces in the name; use underscore instead.)");
for(i=0; i<n; i++){
scanf("%s %d", &list[i], &amount[i]);
sum += amount[i];
}
list[0][n+1] = '\0';
amount[n+1] = '\0';
puts("");
printf("\t\t\t\t Voucher\n\n");
puts(" Ser.|\t Name \t\t\t\t\t\t\t|Amount");
puts("------------------------------------------------------------------------------------------------------------");
for(i=0; i<n; i++ ){
printf(" %03d |\t %-50s\t|%6d\n", i+1, list[i], amount[i]);
}
puts("------------------------------------------------------------------------------------------------------------");
printf(" | Total\t\t\t\t\t\t\t|%6d", sum);
puts("");
return 0;
}
For this you could use the %[ scanf specifier, to read all characters until you hit a digit, and write it into list[i].
This will leave you with a trailing space in list[i], but that can be trimmed if you don't want it.
The scanf call could then look something like
scanf(" %50[^0-9]%d", list[i], &amount[i]);
Note the leading space in the format string, to tell scanf to skip white-space (like the newline from the previous line), and the width-specifier to not read more than can fit in line[i].
Of course, that prevents you from having numbers inside the string you read. To solve this problem you need to go a more complicated route.
For example by reading the whole line into a buffer, and then find the last space in the string. You can then copy the contents before the last space to list[i], and convert the contents after to an int value for amount[i].
I'm trying to read in a grade (1-10) into an array called moduleGrades.
The fgets(moduleGrades[i]-1, sizeof(moduleGrades), stdin); causes an error, yet what i've typed is exactly what I need. I want to store 3 grades (if the number of modules entered was 3)
many thanks.
#include<stdio.h>
#include <string.h>
char name[30];
int moduleNumber;
char moduleGrades[2];
int main(int argc, char **argv)
{ //read name & module amount
printf ("Please enter your name: ");
fgets(name, sizeof(name), stdin);
printf ("How many Modules: ");
scanf("%d", &moduleNumber);
int i;
for (i = 1; i <= moduleNumber; i++)
{
printf ("Please enter module %d grade ", i);
fgets(moduleGrades[i]-1, sizeof(moduleGrades), stdin);
}
printf("%d", moduleGrades[0]);
printf("%d", moduleGrades[1]);
printf("%d", moduleGrades[2]);
return 0;
}
If you want to print three chars, as indicated by your output, then your array must also be able to hold three chars:
char moduleGrades[2];
Also this loop here:
int i;
for (i = 1; i <= moduleNumber; i++)
This isn't wrong in itself because you subtract the 1 you're off inside the loop, but I would do this and just put this instead:
for (int i = 0; i < moduleNumber; i++)
The fgets call inside the loop is wrong. You're giving it a char instead of a pointer to char. Instead of using fgets, I would just use scanf again:
scanf(" %c", &moduleGrades[i]);
When you print those char that you read in, you need to use the %c format specifier, too:
printf("%c", moduleGrades[0]);
This way it'll print the char that you read in earlier. For instance, if you pressed A, it will print A. With %d it will probably print 65, but it's undefined behavior, so anything else than that might happen instead and there's no guarantee on what exactly will happen.
Im doing some work for Uni and wrote a programm which stores Integers in an char Array and converts them to their ASCII Values and prints them at the end. My code did not work before and only started working when i changed "%c" to "%i" in my scanf line. My question: Why does it have to be "%i" when i wanna store those Numbers in an char Array and not an Int Array. Thanks!
My code:
#include <stdio.h>
int main()
{
int i; /counter
char numbers[12];
printf("Please enter 12 Numbers\n");
for(i = 0; i < 12; i++){
printf("please enter the %i. Number\n", i+1);
scanf("%i", &numbers[i]);// <-- changed "%c" to "%i" and it worked.why?
}
for(i = 0; i < 12;i++){
printf("The %i.ASCII value is %i and has the Char %c\n", i+1, numbers[i], numbers[i]);
}
return 0;
}
%c is for reading a single character. So for example if you type in "123", scanf will read '1' into the char variable and leaves the rest in the buffer.
On the other side %i is the specifier for int and will therefore lead to undefined behavior when trying to read in a char.
I think what you are looking for is the %hhi specifier, which reads a number into a char variable.
I have a problem writing code which does the following: declare a struct{char c; int x; } array and load it with scanf via a loop. After it's loaded, a call to function f will be made which will replace every occurrence of digits in the struct's component c with 0, and will return the sum of the digits replaced by zero.
Code and output are below and I have problem that the loop in the function f seems to iterate one time, and it gives out some really weird values.
This is an exam question so I have to use printf, scanf etc. Also I have that exam in an hour so any quick help is appreciated :)
CODE:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX 2
struct par {
char c;
int x;
};
int f(struct par *niz) {
int i;
int n=0;
for(i=0; i<MAX; i++) {
if(isdigit(niz[i].c)) {
niz[i].c = niz[i].c-'0';
printf("niz[i].c = %d\n i = %d", niz[i].c, i);
n=n+niz[i].c;
niz[i].c='0';
}
}
return n;
}
void main() {
int n;
int i;
struct par niz[MAX];
printf("enter\n");
for(i=0; i<MAX; i++) {
scanf("%c", &niz[i].c);
scanf("%d", &niz[i].x);
}
n=f(niz);
for(int i=0; i<MAX; i++) {
printf("%d\n", niz[i].c);
printf("%d\n", niz[i].x);
}
printf("n = %d\n", n);
}
OUTPUT:
enter
2
2
2
niz[i].c = 2
i = 048
2
10
2
n = 2
When you press enter after the first input, the newline is not scanned by scanf and is left in the input buffer. When you then try to read the number scanf sees the newline and not a number so doesn't scan anything.
The simple solution to that is to add a leading space in front of the formats:
scanf(" %c", &niz[i].c);
scanf(" %d", &niz[i].x);
/* ^ */
This tells scanf to skip whitespace.
Use
niz[i].c = getchar();
instead of
scanf("%c", &niz[i].c);
or, you can use other better methods for getting char input discussed at SO,
Now,
You see second time you provided input only once, that is because the Enter you pressed after giving 2 as input to first char remained in input buffer, and was read on second iteration.
You are getting 10 as output, because, it is ASCII for \r, the Enter. It is not a digit, so not replaced to be '0'.
I am looking at your code (i am not using console for a decade, but ) here are some insights:
try to rename MAX with something else
do not know your IDE but sometimes MAX is reserved
and using it as macro can cause problems on some compilers
change scanf("%c", &niz[i].c) to scanf("%c", &(niz[i].c))
just to be shore that correct adsress is send to scanf
change scanf("%d", &niz[i].x) to scanf("%i", &(niz[i].x))
change "%d" to the correct value (this is main your problem)
"%c" for char
"%i" for int
Try to trace line by line and watch for improper variables change if above points does not help
weird values?
because you forgot "\n" after the line, so next print is behind the line "i = %d".
And, check return value of every function except ones that return void.
Basically I have a C program where the user inputs a number (eg. 4). What that is defining is the number of integers that will go into an array (maximum of 10). However I want the user to be able to input them as "1 5 2 6" (for example). I.e. as a white space delimited list.
So far:
#include<stdio.h>;
int main()
{
int no, *noArray[10];
printf("Enter no. of variables for array");
scanf("%d", &no);
printf("Enter the %d values of the array", no);
//this is where I want the scanf to be generated automatically. eg:
scanf("%d %d %d %d", noArray[0], noArray[1], noArray[2], noArray[3]);
return 0;
}
Not sure how I might do this?
Thanks
scanf automatically consumes any whitespace that comes before the format specifier/percentage sign (except in the case of %c, which consumes one character at a time, including whitespace). This means that a line like:
scanf("%d", &no);
actually reads and ignores all the whitespace before the integer you want to read. So you can easily read an arbitrary number of integers separated by whitespace using a for loop:
for(int i = 0; i < no; i++) {
scanf("%d", &noArray[i]);
}
Note that noArray should be an array of ints and you need to pass the address of each element to scanf, as mentioned above. Also you shouldn't have a semicolon after your #include statement. The compiler should give you a warning if not an error for that.
#include <stdio.h>
int main(int argc,char *argv[])
{
int no,noArray[10];
int i = 0;
scanf("%d",&no);
while(no > 10)
{
printf("The no must be smaller than 10,please input again\n");
scanf("%d",&no);
}
for(i = 0;i < no;i++)
{
scanf("%d",&noArray[i]);
}
return 0;
}
You can try it like this.