How to get char from string by index in c language? - c

#include <stdio.h>
int main() {
char str[11];
int num;
scanf("%s %i", &str, &num);
printf("You typed %s and %i\n", str, num);
if (num == 0)
{
printf (str);
}
else
{
printf (str[num]);
}
return 0;
}
The input is a phone number and a digit. If the digit is not 0, then print number[digit].
It the last second line, I tried both str[num] and &str[num]. The first case will cause Segmentation fault (core dumped). The second one will return a string but not a char.
6479378812 1
You typed 6479378812 and 1
479378812
But what I want is the second digit, which is 4. How can I fix it?

You need to specify the formatting string for your printfs. The first needs a string format "%s", the second a single character "%c". You can find all the details about the format used in the formatting string of printf() here.
#include <stdio.h>
int main() {
char str[11];
int num;
scanf("%s %i", &str, &num);
printf("You typed %s and %i\n", str, num);
if (num == 0)
{
printf ("%s", str);
}
else
{
printf ("%c", str[num]);
}
return 0;
}

You have to specify what do you want to print with the printf function.
printf("%c", str[num]);
With %c you tell to the function that you want to print a character.
If you want to print a whole string, you shall use %s.
By the way, you shall always specify the formatting string, because it is unsafe if you do not specify it. https://en.wikipedia.org/wiki/Uncontrolled_format_string

Related

Is there some problem with the following c code

When i compile and run this program my input string is not same as output.
#include<stdio.h>
int main()
{
int n; char ch[100];
scanf("%d : %5s", &n, ch);
printf("%d : %s", n, ch); // there is some problem with output of the string
return 0;
}
input:
45
asdf
output:
45 : ∟sëuⁿ■a
The scanf part will read until it hits the colon, but it will not read the colon itself, which means the following integer will not be read correctly and the rest of the string will be parsed incorrectly (if at all).
Try removing the colon (:) from the scanf
#include <stdio.h>
int main()
{
int n; char ch[100];
scanf("%d %5s", &n, ch);
printf("%d : %s", n, ch);
return 0;
}
get rid of the ":" in scanf(), nothing is read after the "%d" input

Got some segmentation error when use struct pointer in for loop in C

Here is some simple code that prints struct values
in_hotel_info function is used to get struct inputs.(And yes, I use 'gets' because my professor forced me to use it sadly). And also When I put "0" as an input, it ends and returns its input numbers.
And I used sscanf to scan strings and numbers.
#include <stdio.h>
typedef struct hotel_info hotel;
struct hotel_info
{
char name[30];
int rank;
double popular;
double far;
char breakfast;
};
int in_hotel_info(struct hotel_info *p);
void out_hotel_info(struct hotel_info *p, int N, int G, double D);
int main(void)
{
hotel hotels[100];
hotel *p;
int number = 0, ranks, fars, i;
number = in_hotel_info(hotels);
p = hotels;
printf("%d\n", number);
getchar();
for (; p < p+number; p++)
{
printf("%s %d %lf %lf %c\n", p->name, p->rank, p->popular, p->far, p->breakfast);
}
}
int in_hotel_info(struct hotel_info infos[])
{
char inputs[100];
hotel* p;
p = infos;
int cnt = 0;
while (1)
{
gets(inputs);
if (strcmp(inputs, "0") == 0)
{
break;
}
else
{
sscanf(inputs, "%s %d %lf %lf %c", p->name, &p->rank, &p->popular, &p->far, &p->breakfast);
}
p++;
cnt++;
}
return cnt;
}
The problem is, when I tried to print
for (; p < p+number; p++)
{
printf("%s %d %lf %lf %c\n", p->name, p->rank, p->popular, p->far, p->breakfast);
}
what I expected is
mike 2 3.5 4.24 Y
but I constantly got a segmentation error.
The problem is, when I tried to print
for (; p < p+number; p++)
{
printf("%s %d %lf %lf %c\n", p->name, p->rank, p->popular, p->far, p->breakfast);
}
the problem is p < p+number is always true when number is strictly positive, so the for never ends and you access out of the array with an undefined behavior (your segmentation fault).
you have additional problems
gets is very dangerous to use because it can write out of the array, use fgets or scanf (secifying max length to read), in the considered case you can read a number then check if it is 0 or not
in in_hotel_info in case the user enter more than than entrie you write out of the array, you need to get the max number of element to read in argument
when you read p->name in case the enter name longer than 29 you write out of the array, limit the size using %29s rather than %s. ALso to bypass spaces at the beginning of the name use %29s (with a space before)
you do not check scanf returns 5, so you do not detect invalid inputs
The getchar(); in main is strange

Storing Integers in an Char Array in C

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.

A user types a word and a number on a single line. Read them into the provided variables. Then print

It takes in a word and a number, I can't seem to understand why the number variable won't receive the input, help please.
#include <stdio.h>
int main(void) {
char userWord[20];
int userNum;
scanf("%s", userWord);
printf("%s_", userWord);
scanf("%s", userNum);
printf("%d\n", userNum);
return 0;
}
Should be:
Input: Stop 7
Output: Stop_7
What I get:
Input: Stop 7
Output: Stop_0
Change
scanf("%s", userNum);
to
scanf("%d", &userNum);
You used format %s for reading in an integral value; it should have been %d.
Once having fixed this (i.e. by writing scanf("%d", &userNum);, note that your code will read in a string and a number even if the string and the number were not in the same line (cf., for example, cppreferene/scanf concerning format %s and treatment of white spaces). Further, you will run into undefined behaviour if a user enters a string with more than 19 characters (without any white space in between), because you then exceed your userWord-array.
To overcome both, you could read in a line with fgets, then use sscanf to parse the line. Note that you can parse the line in one command; the result of scanf is then the number of successfully read items. Further, note the %19s, which limits the input to 19 characters (+ the final string termination character '\0'):
int main() {
char line[100];
if (fgets(line,100,stdin)) {
char userWord[20];
int userNum;
if (sscanf(line, "%19s %d", userWord, &userNum) != 2) {
printf("invalid input.\n");
} else {
printf("word:'%s'; number: %d", userWord, userNum);
}
}
}

While Loop will not Execute in C

When I run this program, everything is executed except for the block of while loops at the end. I am asked for the "number of symbols to print per line" and then the program ends. Any help would be greatly appreciated.
#include <stdio.h>
int main(void) {
int num_lines;
printf("Enter a number of lines, greater than or equal to 7, to print : ");
scanf("%d", &num_lines);
if (num_lines < 7) {
while ( num_lines < 7 ) {
printf("Enter the number of lines to print\nMust be greater than or equal to 7 : ");
scanf("%d", &num_lines);
}
}
char symbol;
printf("Choose a symbol/character to be displayed */&/+/0/x : ");
scanf("%s", &symbol);
int num_symbols;
printf("Enter the number of symbols to print per line : ");
scanf("%d", &num_symbols);
if (num_symbols < 7 || num_symbols > 27) {
num_symbols = 19;
}
while (num_lines > 0) {
while (num_symbols > 0) {
printf("%s", symbol);
--num_symbols;
}
printf("\n");
--num_lines;
}
return;
}
In this code snippet
char symbol;
printf("Choose a symbol/character to be displayed */&/+/0/x : ");
scanf("%s", &symbol);
there is used invalid format specifier %s. Instead use format specifier " %c"
char symbol;
printf("Choose a symbol/character to be displayed */&/+/0/x : ");
scanf(" %c", &symbol);
Also in this call of printf
printf("%s", symbol);
you have to use the format specifier %c
printf("%c", symbol);
To provide that these loops would work correctly
while (num_lines > 0) {
while (num_symbols > 0) {
printf("%s", symbol);
--num_symbols;
}
printf("\n");
--num_lines;
}
you need to use an intermediate variable to store the value of num_symbols between iterations of the outer loop. For example
while (num_lines > 0) {
int n = num_symbols;
while (n > 0) {
printf("%c", symbol);
--n;
}
printf("\n");
--num_lines;
}
Your code has a very severe bug,
char symbol;
scanf("%s", &symbol);
is undefined behavior, because "%s" expects a pointer to a char array of at least size 2. In your case, you are passing a pointer to a single char, the effects of such code is undefined.
Instead, it could be (at least)
char symbol[2];
scanf("%1s", symbol);
Or, see #BLUEPIXY's suggestion.
After invoking undefined behavior, the program's memory could become corrupted so the rest of the program could fail for multiple reasons.
You also, never check that scanf("%d", ...) was succesful potentially another cause for undefined behavior.
ALWAYS check that scanf() returns the right value.
Let's boil the problem down to it's core: you're overwriting num_lines on the call stack because you're asking to read a string when you really want a character. When scanf creates the string, it will be null terminated ... and so add a null character after the single char on the stack. One of the joys of working with pointers in C.
(This isn't a stack overflow but rather just a stack overwrite.)
Here is a minimal example of failure. Just change the %s to %c and everything will work:
#include <stdio.h>
int main(void) {
int num_lines;
sscanf("7", "%d", &num_lines);
printf("at first, num_lines is %d\n", num_lines);
char symbol;
sscanf("x", "%s", &symbol);
printf("but now, num_lines has become %d\n", num_lines);
printf("value changed because the second sscanf overwrote\n");
printf(" num_lines on the call stack!!!\n");
return;
}
You'll notice that I'm lazy; use sscanf during testing to have less annoying typing to perform.
Run it and you get:
$ gcc scan.c ; ./a.out
at first, num_lines is 7
but now, num_lines has become 0
value changed because the second sscanf overwrote
num_lines on the call stack!!!
Your problem is with char variable symbol. You are declaring symbol as character variable and reading it as string. There is one more issue. While you are using scanf to read string or character and number at the same time always read the string or char value before reading a numeric value. The reason is scanf also read one more character \n for which it always creates problem.
now change your code like below:-
#include <stdio.h>
int main(void) {
int num_lines;
char symbol;
printf("Choose a symbol/character to be displayed */&/+/0/x : ");
scanf("%c", &symbol);
printf("Enter a number of lines, greater than or equal to 7, to print : ");
scanf("%d", &num_lines);
if (num_lines < 7) {
while ( num_lines < 7 ) {
printf("Enter the number of lines to print\nMust be greater than or equal to 7 : ");
scanf("%d", &num_lines);
}
}
int num_symbols;
printf("Enter the number of symbols to print per line : ");
scanf("%d", &num_symbols);
if (num_symbols < 7 || num_symbols > 27) {
num_symbols = 19;
}
while (num_lines > 0) {
while (num_symbols > 0) {
printf("%s", symbol);
--num_symbols;
}
printf("\n");
--num_lines;
}
return 0;//you have to return a value
}
if still giving you any problem just hard coded symbol = '*'; and try.

Resources