Find the character of a string by inputting the position in c - c

Hi I know that there are alot of examples where you input a character to and output the position of the character. But how do you do it the other way around where you input the position and output the character ?
input string: abcdefghijklmnopqrstuvwxyz
input position: 0
output: The character in position 0 is 'a'
Do I use atoi?
int main(void) {
char line[SIZE];
int position;
// int character = getchar(); //get string
scanf("%d\n", &position); //get position
int i = 0;
while(fgets(line, SIZE, stdin) != NULL) {
if(line[i] == position) {
printf("The character in postion %d is '%c'\n", position,line[i]);
//flag = TRUE;
// }
i++;
}
return 0;
}

while(fgets(line, SIZE, stdin) != NULL)
{
line[strlen(line)-1] = '\0'; // as fgets append '\n' before '\0', replacing '\n' with '\0'
if(strlen(line) > position)
{
printf("The character in postion %d is '%c'\n", position,line[position]);
}
else
{
printf("invalid position\n");
}
}

You probably want this:
#include <stdio.h>
#define SIZE 100
int main(void) {
char line[SIZE];
int position;
scanf("%d", &position); //get position
getchar(); // absorb \n from scanf (yes scanf is somewhat odd)
while (fgets(line, SIZE, stdin) != NULL) {
printf("The character in postion %d is '%c'\n", position, line[position]);
}
return 0;
}
No out of range check whatsoever is done here for brevity
Example of execution:
1
abc
The character in postion 1 is 'b'
Hello
The character in postion 1 is 'e'
TEST
The character in postion 1 is 'E'
This small example may help too:
#include <stdio.h>
#define SIZE 100
int main(void) {
char line[SIZE];
fgets(line, SIZE, stdin);
for (int i = 0; line[i] != 0; i++)
{
printf("The character in postion %d is '%c'\n", i, line[i]);
}
}
No error checks done either for brevity.

Related

How do I let the user multiply two numbers as well as let them multiply a string?

What I mean by this is, I'm writing a program where the user inputs a string along with a '*' character and any number, and the program multiplies the string the user entered by that number
Please enter a string you'd like multiplied: horse*3
output:
horsehorsehorse
What I'd like to do is, if that string happens to be a number, then multiply the two numbers like you normally would
Please enter a string you'd like multiplied: 2*2
output:
4
I'm putting my code down below.
int multStr(char *strMult) //strMult is character array for initial input
{
//printf("\nRedirected to here!\n");
printf("Please enter a string and number you'd like to multiply by: ");
scanf(" %[^\n]s", strMult); //User scans in the string intended for multiplication
char string[255]; //Character array for the string part
char number[255]; //Character array for the number the string is to be multiplied by
int counter=0;
int i;
for(i=0;strMult[i] != '*'; i++)
{
string[i] = strMult[i];
counter++;
}
if(string[i] >= '0' && string[i] <= '9')
{
int strNum = myAtoi(string);
printf("String: %d", strNum);
}
else
{
printf("String: %s\n", string);
}
counter++;
for(i=0; strMult[counter] != '\0'; counter++, i++)
{
number[i] = strMult[counter];
}
//number[i+1] = '\0';
printf("Number: %s\n", number);
int num = myAtoi(number);
//printf("Number after convert: %d\n", num);
for(i=0; i<num; i++)
{
printf("%s", string);
}
printf("\n");
return(0);
}
strMult is a char array I called from main. I was not able to use stdlib, so I created my own Atoi function
You have a couple issues here. The first thing you're doing is splitting the string into two char[]s string and number. You seem to do that ok. The next thing you need to do is to check that string is a number.
if(string[i] >= '0' && string[i] <= '9')
{
int strNum = myAtoi(string);
printf("String: %d", strNum);
}
else
{
printf("String: %s\n", string);
}
This is what you're using, but note that it has no consequence to the rest of the program. Your number is local to the if block, and then it goes away, so you cannot use it later. What you want to do, is make the number available later.
int isNumber = 1;
int strNum;
for(int k = 0; k < i; k++){
if( string[k] >= '0' && string[k]<='9' ){
//continue checking
}else{
isNumber=0;
}
}
if (isNumber==1){
strNum = myAtoi(string);
} else{
// print your string or some such.
}
Note that I check all of the characters in the string, and not just the '*' which is the character at the i'th position. That way, if somebody enters horse42*2, it will think it is a string.
Also, you can improve this by checking the values as you separate out the number.
Regular expressions are a useful tool for parsing user input. Reading unconstrained user input with scanf is dangerous because unexpectedly long input will overflow the buffer.
Here is an example that use getline for reading input safely and regular expressions to sort out the format for the user input.
#include <regex.h>
#include <stdio.h>
#include <stdlib.h>
#define TERM "(([[:digit:]]+)|([[:alpha:]]+))"
void string_by_number(int number, char *string)
{
printf("number %d string %s\n", number, string);
for (int i = 0; i < number; ++i) {
printf("%s", string);
}
printf("\n");
}
int main(int argc, char *argv[])
{
regex_t re;
regmatch_t capture[7];
if (regcomp(&re, TERM "[[:space:]]*[*][[:space:]]*" TERM, REG_EXTENDED)) {
fprintf(stderr, "error in regular expression pattern\n");
return 1;
}
char *line = NULL;
size_t line_size = 0;
printf("Please enter a string you'd like multiplied: ");
while (0 < getline(&line, &line_size, stdin)) {
if (regexec(&re, line, 7, capture, 0)) {
printf("Unexpected input '%s'\n", line);
continue;
}
int format = 0;
char *lhs_string = NULL;
int lhs_number;
char *rhs_string = NULL;
int rhs_number;
if (capture[2].rm_so >= 0) {
format ^= 0x01;
lhs_number = strtol(&line[capture[2].rm_so], NULL, 10);
}
else {
lhs_string = &line[capture[3].rm_so];
line[capture[3].rm_eo] = '\0';
}
if (capture[5].rm_so >= 0) {
format ^= 0x02;
rhs_number = strtol(&line[capture[5].rm_so], NULL, 10);
}
else {
rhs_string = &line[capture[6].rm_so];
line[capture[6].rm_eo] = '\0';
}
switch (format) {
case 0x00: printf("Can't do 'string' * 'string'\n"); break;
case 0x01: string_by_number(lhs_number, rhs_string); break;
case 0x02: string_by_number(rhs_number, lhs_string); break;
case 0x03: printf("%d\n", lhs_number * rhs_number); break;
}
printf("\nPlease enter a string you'd like multiplied: ");
}
free(line);
regfree(&re);
return 0;
}

Trouble comparing a single Char with an array of Chars

I've been getting the error: "subscripted value is neither an array nor pointer nor vector" for my code on line 14. It seems like it should be able to compare the value in the array to the char since they are both primitive data yet I can't seem to get it right:
#include <stdio.h>
#include <string.h>
char str[80];
char ch;
int cnt =0;
int suffix ( str, ch) {
int i=0;
while (strchr(str+i, ch) != NULL){
if (ch == str[i] ){
printf("\n %s \n", str+i);
cnt += 1;
}
i++;
}
return cnt;
}
int main() {
printf("\n Please type a single character and then press ENTER: \n");
ch = getchar();
printf("\n You have typed in the character \" %c \".\n", ch);
printf("\n Now please enter a string. Press ENTER to confirm: \n");
scanf("%s", str);
printf("\n The String you typed in is: %s.", str);
suffix(str, ch);
printf("The character \" %c \" appeares %d times in the string. \n", ch, cnt);
return 0;
}
The problem is that you are declaring the function like this:
int suffix ( str, ch)
{
...
}
without telling the compiler the type of str and ch. So the compiler assumes
they are int, and you cannot use [] on an int. You have to declare the
functions like this
int suffix(char *str, char ch)
{
...
}
And why are you declaring str, ch and cnt as global variables? There is
absoulutly no reason for that.
So the program should look like this:
#include <stdio.h>
#include <string.h>
// const char is even better, because you are not modifying the string
int suffix (const char *str, char ch) {
int cnt = 0;
int i=0;
while (strchr(str+i, ch) != NULL){
if (ch == str[i] ){
printf("\n %s \n", str+i);
cnt += 1;
}
i++;
}
return cnt;
}
void clean_stdin(void)
{
int ch;
while((ch = getchar()) != '\n' && ch != EOF);
}
int main() {
int ch;
int cnt;
char str[100];
printf("\n Please type a single character and then press ENTER: \n");
ch = getchar();
printf("\n You have typed in the character \" %c \".\n", ch);
clean_stdin(); // to get rid of the newline in the input buffer
// or if the user typed more than a single character
printf("\n Now please enter a string. Press ENTER to confirm: \n");
scanf("%99s", str);
printf("\n The String you typed in is: %s.", str);
cnt = suffix(str, ch);
printf("The character \" %c \" appeares %d times in the string. \n", ch, cnt);
return 0;
}

Keep characters in an array

I want to do a program that ask to the user to give one character, then enter... until he wants to stop by pressing enter and no caracters.
Then, the program will say: "you gave the caracters ...."
for example:
give the caracter 1: k + enter
give the caracter 2: l + enter
give the caracter 3: just enter ('\n')
result: You gave the caracters: kl
My code doesnet work because when i just press enter, nothing happen. Here is the code:
#include <stdio.h>
#define N 1000
int main() {
int i = 0;
int j = 0;
char str[N];
while (str[i] != '\n') {
printf("element number str[%d] : ", i);
scanf("%s", &str[i]);
i++;
}
printf("The string is: ");
while (j < i) {
printf("%s", str[j]);
j += 1;
}
return 0;
}
You can do it with c = getchar(); or c = fgetc(stdin) function:
#include <stdio.h>
#define N 1000
int
main ()
{
int i = 0;
int j = 0;
int c;
char str[N];
while (1)
{
c = fgetc(stdin); // or c = getchar();
if ( (c != EOF) && (c != 0x0A ) ) // 0x0A = 'nl' character
{
str[i] = (char) c;
printf ("element number str[%d]=%c \n", i, str[i++] );
}
else
{
str[i] = 0;
break;
}
}
printf ("The string is: %s", str);
return 0;
}
OUTPUT:
This is my string!
element number str[1]=T
element number str[2]=h
element number str[3]=i
element number str[4]=s
element number str[5]=
element number str[6]=i
element number str[7]=s
element number str[8]=
element number str[9]=m
element number str[10]=y
element number str[11]=
element number str[12]=s
element number str[13]=t
element number str[14]=r
element number str[15]=i
element number str[16]=n
element number str[17]=g
element number str[18]=!
The string is: This is my string!
Or you can use your original scanf("%s", &str1);
#include <stdio.h>
#define N 1000
int main ()
{
int i = 0;
int k = 0;
int c;
int len;
char str[N];
char str1[N];
scanf("%s", &str1);
len = strlen(str1);
for(k = 0; k < len; k++)
{
c = str1[k];
if ( (c != EOF) && c != '\n') // EOF will work for ^D on UNIX
{
str[i] = (char) c;
printf ("element number str[%d]=%c \n", i, str[i++] );
}
else
{
str[i] = 0;
break;
}
}
printf ("The string is: %s", str);
return 0;
}
OUTPUT:
12345
element number str[1]=1
element number str[2]=2
element number str[3]=3
element number str[4]=4
element number str[5]=5
The string is: 12345
As stated in this answer scanf will not return until you give it a string, i.e. it skips whitespace.
As suggested in the answer and in general, using fgets is the better option.
Edit: A way to accomplish what you want would look like this:
#include <stdio.h>
#define N 1000
int main() {
int i = 0;
int j = 0;
char str[N];
do {
printf("element number str[%d] : ", i);
fgets(&str[i], 3, stdin);
i++;
} while (str[i - 1] != '\n');
printf("The string is: ");
while (i > j) {
printf("%c", str[j]);
j++;
}
return 0;
}
In the fgets you use the number 3 because pressing enter gives both a newline character [/n] and a return carriage [/r].

Maximum number of Characters in a character array

//Program to find max occurring character in string
#include<stdio.h>
#include<conio.h>
#define MAX_SIZE 100 // Maximum string size, change to make string smaller or larger
#define MAX_CHARS 255 // Maximum characters allowed for characters
void main()
{
char str[MAX_SIZE]; //store the string
int freq[MAX_CHARS]; // store frequency of each character
int i, max; // i is for loop max to store frequency
int ascii; //stores ascii value convertd from each char
char ch; //for choice
do{
clrscr();
i=0;
printf("\nEnter any string: ");
gets(str);
// Initializes frequency of all characters to 0
for(i=0; i<MAX_CHARS; i++)
{
freq[i] = 0;
}
// Finds occurance/frequency of each characters
i=0;
while(str[i] != '\0')
{
ascii = (int)str[i];
freq[ascii] += 1; //string's element is casted to int to store its ascii value for further comparision
i++;
}
// Finds maximum frequency of character
max = 0;
for(i=0; i<MAX_CHARS; i++)
{
if(freq[i] > freq[max])
max = i; //to print no. of times
}
printf("\nMaximum occurring character is '%c' = %d times.", max, freq[max]);
printf("\n Want to find again??(y/n):");
scanf("%c",&ch);
}while(ch=='Y'||ch=='y');
}
When I give it the input: "aaaaeeee", the output is "a" occurring 4 times, but "e" occurs 4 times too. I know this is sorted by ascii values and thats why it gives "a" as output, but what can I do in this program that the output gives both "a" and "e" as output when a case like this occurs?
Add max calculation ahead
i = 0;
max = 0;
while(str[i] != '\0')
{
ascii = (int)str[i];
freq[ascii] += 1;
if (freq[ascii] > max) max = freq[ascii]; // <==== here
i++;
}
Note that this is the max number of the same character you might have.
Then display all chars which maximum is equal to max
for(i=0; i<MAX_CHARS; i++)
{
if(freq[i] == max) printf("Character %c is at max %d\n", i, max);
}
To fix the endless loop, before the while add char c ; while ((c = getchar()) != EOF && c != '\n');
scanf("%c",&ch);
char c;
while ((c = getchar()) != EOF && c != '\n'); // <== note the ';'
} while(ch=='Y'||ch=='y');
Note that you shouldn't use gets, reason is explained here.
Whole code:
void main()
{
char str[MAX_SIZE]; //store the string
int freq[MAX_CHARS]; // store frequency of each character
int i, max; // i is for loop max to store frequency
int ascii; //stores ascii value convertd from each char
char ch; //for choice
do {
printf("\nEnter any string: ");
gets(str);
// Initializes frequency of all characters to 0
for(i=0; i<MAX_CHARS; i++)
{
freq[i] = 0;
}
// Finds occurance/frequency of each characters
for(i=0,max=0 ; str[i] != '\0' ; i++)
{
ascii = (int)str[i];
freq[ascii] += 1; //string's element is casted to int to store its ascii value for further comparision
if (freq[ascii] > max) max = freq[ascii];
}
for(i=0; i<MAX_CHARS; i++)
{
if(freq[i] == max) printf("Character %c is at max %d\n", i, max);
}
printf("\n Want to find again??(y/n):");
scanf("%c",&ch);
char c;
while ((c = getchar()) != EOF && c != '\n');
}while(ch=='Y'||ch=='y');
}
Above this line
printf("\nMaximum occurring character is '%c' = %d times.", max, freq[max]);
Delete it and add this code
for(i=0;i<MAX_CHARS;i++)
{
if(freq[i]==freq[max])
{
printf("\nMaximum occurring character is '%c' = %d times.", i, freq[i]);
}
}

dealing with string input in C

I am trying to input string into fixed size char array.
I have a questions:
when I input a string which is bigger than the char array, the array become bigger without any additional declaration. I want to make the code only take the string that 'equal or smaller than the char array'.
Thank You.
CODE:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
/***************************Function****************************/
int string_length(char s[]) {
int c = 0;
while (s[c] != '\0')
c++;
return c;
}
/**************************************************************/
char *str;
int arrSize;
void opt1()
{
printf("Enter array size: ");
scanf("%d", &arrSize);
arrSize=arrSize+1;
str = malloc(arrSize);
return;
}
void opt2()
{
printf("Enter characters: ");
scanf("%s", str);
length = string_length(str);
printf("your input is '%s'\n", str);
printf("your input length is '%d'\n", length);
return;
}
int main()
{
int input = 0;
while(input != 3) {
printf("\n NAME \n");
printf("\n");
printf("--------------------------------------\n");
printf("1) Making Array \n");
printf("2) Check Array \n");
printf("3) Quit\n");
printf("\nEnter selection: ");
scanf("%d", &input);
if( input == 1 ) {
/* */
opt1();
}
else if(input == 2) {
opt2();
}
}
return 1;
}
OP wants to read data, yet if larger that the target array, then do not change the target array.
// 1: success
// -1 EOF
// 0: Input too long
int read_array(char *buffer, size_t size) {
char tmp[size];
size_t i = 0;
int ch;
while ((ch = fgetc(stdin)) != EOF && ch != '\n') {
if (i < size) {
tmp[i++] = ch;
}
}
if (ch == EOF && i == 0) return EOF;
if (i >= size) return 0; // too many
memcpy(buffer, tmp, i);
buffer[i] = '\0';
return 1;
}
Normally code could use fgets(), but there are corner cases that fail to meet OP goals.
To read in a whole line, you can use fgets:
char line[80];
if (fgets(line, sizeof line, stdin) != NULL) {
// use the input
}
Now you won't need to check if the user entered more than the limit, since fgets will only get the first 79 (-1 for null terminator) characters; the remainder, if any, will be ignored.

Resources