I try to learn C Language and something is not clear to me.
I want to write IndexOf function that search for char inside string and return the Index number.
I am running this under ubuntu and compile using this:
test1: test.c
gcc -g -Wall -ansi -pedantic test.c -o myprog1
This is what i have try:
int c;
int result;
printf("Please enter string: ");
scanf("%s", str1);
printf("Please enter char: ");
scanf("%d", &c);
result = indexof(str1, c);
printf("Result value: %d\n", result);
And this is my function:
int indexof(char *str, int c)
{
int i;
for (i = 0; i < strlen(str); i++)
{
if (str[i] == c)
return i;
}
return -1;
}
So my problem is that my function return -1 all the time
scanf("%c",&c)..you are getting input a character.
Working copy would besomethign like:-
char c; // you want to find the character not some integer.
int result;
printf("Please enter string: ");
scanf("%s", str1);
printf("Please enter char: ");
scanf("%d", &c);
result = indexof(str1, c);
printf("Result value: %d\n", result);
Working example:-
#include <stdio.h>
#include <string.h>
int indexof(char *str, char c)
{
int i;
for (i = 0; i < strlen(str); i++)
{
if (str[i] == c)
return i;
}
return -1;
}
int main()
{
char c;
int result;
char str1[100];
printf("Please enter string: ");
scanf("%s", str1);
printf("Please enter char: ");
scanf(" %c", &c);
result = indexof(str1, c);
printf("Result value: %d\n", result);
}
Since c is int:
int indexof(char *str, int c)
{
int i;
for (i = 0; i < strlen(str); i++)
{
if ((str[i]-'0') == c) // convert char to int
return i;
}
return -1;
}
write IndexOf function that search for char inside string and return the Index number.
You might like to have a look at the strchr() function, which can be used as shown below:
/* Looks up c in s and return the 0 based index */
/* or (size_t) -1 on error of if c is not found. */
#include <string.h> /* for strchr() */
#include <errno.h> /* for errno */
size_t index_of(const char * s, char c)
{
size_t result = (size_t) -1; /* Be pessimistic. */
if (NULL == s)
{
errno = EINVAL;
}
else
{
char * pc = strchr(s, c);
if (NULL != pc)
{
result = pc - s;
}
else
{
errno = 0;
}
}
return result;
}
You could call it like this:
size_t index_of(const char *, char);
#include <stdlib.h> /* for EXIT_xxx macros */
#include <stdio.h> /* for fprintf(), perror() */
#include <errno.h> /* for errno */
int main(void)
{
result = EXIT_SUCCESS;
char s[] = "hello, world!";
char c = 'w';
size_t index = index_of(s, 'w');
if ((size_t) -1) == index)
{
result = EXIT_FAILURE;
if (0 == errno)
{
fprintf("Character '%c' not found in '%s'.\n", c, s);
}
else
{
perror("index_of() failed");
}
}
else
{
fprintf("Character '%c' is at index %zu in '%s'.\n", c, index, s);
}
return result;
}
Related
After i put a name in the terminal and it is shorter, then 20 chars, it wants inputs until i have filled all the 20 positions in the array.
I know it is because of the for cycle i have there, but I don't know how else to fill that end of the array with nothing("").
In the array there is for example this "Helloworld\n123\n123"
Thank you for help in advance.
#define NAME 20
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
main(void) {
char name[NAME] = {""};
malloc(sizeof(name[NAME]));
printf("Choose your name: ");
for (int i = 0; i < NAME; i++) {
scanf("%c", &name[i]);
}
//Welcome and the name
printf("Welcome: ");
for (int i = 0; i < NAME; i++) {
printf("%c", name[i]);
}
return 0;
}
You need to stop reading at a newline (+should also check return codes).
A loop like:
size_t i=0;
for (; i < sizeof(name)-1; i++) {
if (1==(scanf("%c",&name[i]))){ if (name[i]=='\n') break; }
else if (feof(stdin)) break; //end of file?
else return perror("getchar"),1; //report error
}
name[i]='\0';
will achieve that (can also use getchar/getc/fgetc instead of scanf)
or you can use fgets:
if(NULL==fgets(name,sizeof(name),stdin)) return perror("fgets"),1;
//erase a possibly included newline at the end
//(won't be there if you pressed Ctrl+D twice rather than
//Enter to submit your input or if you're at the end of
//a stdin redirected from a file)
size_t len = strlen(name);
if(name[len-1]=='\n') name[len-1]='\0';
Whole program with both versions (in the if(0){...}else{...}) :
#define NAME 20
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
int main(void) {
char name[NAME] = {""};
//malloc(sizeof(name[NAME])); //a useless memory leak; don't do this!
printf("Choose your name: ");
if(0){
if(NULL==fgets(name,sizeof(name),stdin)) return perror("fgets"),1;
size_t len = strlen(name);
if(name[len-1]=='\n') name[len-1]='\0';
}else{
size_t i=0;
for (; i < sizeof(name)-1; i++) {
if (1==(scanf("%c",&name[i]))){ if (name[i]=='\n') break; }
else if (feof(stdin)) break; //end of file?
else return perror("getchar"),1;
}
name[i]='\0';
}
//Welcome and the name
printf("Welcome: ");
for (int i = 0; i < NAME; i++) {
printf("%c", name[i]);
}
return 0;
}
If you have to use scanf and %c format:
char *readLineUsingCharAndScanf(char *buff, size_t size, FILE *fi)
{
char ch;
char *wrk = buff;
while(size-- && fscanf(fi, "%c", &ch) == 1 && ch != '\n' ) *wrk++ = ch;
*wrk = 0;
return buff;
}
void dumpString(const char *restrict str, size_t size)
{
while(*str && size--)
{
printf("%03d [0x%02x] - %s\n", *str, *str, (*str >= 32 & *str <= 127) ? (char[]){'\'', *str, '\'', 0} : "not printable");
str++;
}
}
int main(void)
{
char name[20];
dumpString(readLineUsingCharAndScanf(name, 19, stdin), 20);
}
https://godbolt.org/z/vWvP68TbW
scanf() is not the best tool for your purpose. Here is a simple and safe solution:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#define NAME 20
int main(void) {
char name[NAME];
int c;
size_t i;
printf("Enter your name: ");
i = 0;
while ((c = getchar()) != EOF && c != '\n') {
if (i < sizeof(name) - 1)
name[i++] = c;
}
name[i] = '\0';
//Welcome and the name
printf("Welcome: %s\n", name);
return 0;
}
If you must use scanf(), use this:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#define NAME 20
int main(void) {
char name[NAME];
char c;
size_t i;
printf("Enter your name: ");
i = 0;
while (scanf("%c", &c) == 1 && c != '\n') {
if (i < sizeof(name) - 1)
name[i++] = c;
}
name[i] = '\0';
//Welcome and the name
printf("Welcome: %s\n", name);
return 0;
}
Thank you everyone for answering. Unfortunately the first two answers are too complicated for me yet. And the third one was not working properly.
But I found the simplest answer. :) Many thanks
#include <stdio.h>
int main(void)
{
char name[20];
printf("Choose your name: ");
scanf("%[^\n]*c",name);
printf("My name is %s",name);
}
For your needs I would use scanf with the string conversion specifier %s. In this case, the input name would be read and stored character by character in the buffer until the whitespace would be read. Here is the code.
#define NAME 20
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char name[NAME] = {""};
malloc(sizeof(name[NAME]));
printf("Choose your name: ");
scanf("%s", &name);
printf("%s", &name);
return 0;
}
I tried making a small program that would detect if you typed in a palindrome but for some reason, it just loops
ps I'm a beginner
#include <stdio.h>
#include <string.h>
int main(void)
{
char arr[100], arr1[100];
int i;
printf("type in a string\n\n");
gets(arr);
strrev(arr) == arr1;
for (i=0; arr==arr1; i++)
{
printf("%c is a palindrome\n", arr);
}
for (i=0; arr!=arr1; i++)
{
printf("%c is not a palindrome\n", arr);
}
return 0;
}
arr and arr1 are base address of the two arrays respectively which would be different.One simple Code is here
#include <stdio.h>
#include <string.h>
int main(void)
{
char arr[100], arr1[100];
int i;
printf("type in a string\n\n");
gets(arr);
int len=strlen(arr);
strcpy(arr1,arr);
strrev(arr);
for(i=0;i<len;i++){
if(arr1[i]!=arr[i]){
printf("Not palindrome");
return 1;
}
}
printf("Palindrome");
return 0;
}
Use fgets instead of gets.
The first character could be compared to the last character. Then move the indexes toward the center for subsequent comparisons.
#include <stdio.h>
#include <string.h>
int main(void) {
char arr[100] = "";
int first = 0;
int last = 0;
printf ( "type in a string\n\n");
if ( !fgets ( arr, sizeof arr, stdin)) {
printf ( "fgets problem\n");
return 0;
}
arr[strcspn ( arr, "\n")] = '\0';//remove newline
for ( first = 0, last = strlen ( arr) - 1; first <= last; first++, last--) {
if ( arr[first] != arr[last]) {
printf("%s is not a palindrome\n", arr);
return 0;
}
}
printf ( "%s is a palindrome\n", arr);
return 0;
}
What I'm trying to do is have the user input a hex number this number will then be converted to a char and displayed to the monitor this will continue until an EOF is encountered.I have the opposite of this code done which converts a char to a hex number. The problem I'm running into is how do i get a hex number from the user I used getchar() for the char2hex program. Is there any similar function for hex numbers?
this is the code for the char2hex program
#include <stdio.h>
int main(void) {
char myChar;
int counter = 0;
while (EOF != (myChar = getchar())) {
/* don't convert newline into hex */
if (myChar == '\n')
continue;
printf("%02x ", myChar);
if (counter > 18) {
printf("\n");
counter = -1;
}
counter++;
}
system("pause");
return 0;
}
this is what i want to the program to do except it would do this continuously
#include <stdio.h>
int main() {
char myChar;
printf("Enter any hex number: ");
scanf("%x", &myChar);
printf("Equivalent Char is: %c\n", myChar);
system("pause");
return 0;
}
any help would be appreciated
thank you
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(void) {
int myChar;
int counter = 0;
char buff[3] = {0};
while (EOF != (myChar = getchar())) {
if(isxdigit(myChar)){
buff[counter++] = myChar;
if(counter == 2){
counter = 0;
myChar = strtol(buff, NULL, 16);
putchar(myChar);
}
}
}
printf("\n");
system("pause");
return 0;
}
Because chars and ints can be used interchangably in C, you can use the following code:
int main(void) {
int myChar;
printf("Enter any hex number: ");
scanf("%x", &myChar);
printf("Equivalent Char is: %c\n", myChar);
system("pause");
return 0;
}
If you want it to loop then just enclose it in the while loop as in your example code.
Edit: You can try out the working code here http://ideone.com/yyvz85
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 24
void rez(char **c, char *s, int n, int ks);
void rez(char **c, char *s, int n, int ks)
{
int t = 0, j = 0;
char *p;
p = strtok(s," ");
t = t + strlen(p);
if (strlen(p)>N) *(c+j)=(char*)malloc((strlen(p)+1)*sizeof(char));
else *(c+j)=(char*)malloc((N+1)*sizeof(char));
while(p!=NULL)
{
if (t>N)
{
*(*(c+j)+t) = '\0';
t = strlen(p) + 1;
j++;
if (t>N) *(c+j)=(char*)malloc(strlen(p)+1);
else *(c+j)=(char*)malloc(N+1);
}
strcat(*(c+j), p);
c[j][t]=' ';
p = strtok(NULL, " ");
t=t+strlen(p)+1;
}
c[j][t]='\0';
for(j=0; j<ks; j++)
{
printf("\n %s", *(c+j));
}
}
int main(void)
{
FILE *fin;
int n, ks;
char s1[2048], filename[256];
char **c;
printf("Enter the file name->");
scanf("%s", filename);
fin=fopen(filename,"r");
if (!fin)
{
printf ("Error\n");
return -1;
}
while (fscanf(fin, "%[^\n]", s1)==1)
{
fscanf(fin, "%*[ \n]");
printf("\n String: %s \n", s1);
n=strlen(s1);
ks=n/(N-1)+1;
c=(char **)malloc(ks*sizeof(char*));
rez(c, s1, n, ks);
}
fclose(fin);
return 0;
}
This code should cut long strings into some shorter, but it gives "core dumped" in gcc. It doesn't exit from while in void rez().
In my mind, strtok() works incorrectly.
This is wrong:
char r[1]=" ";
because the string literal " " is TWO characters! It is both a space and a NULL-terminator (which is at the end of every string in C. But you explicitly said it should only be a 1 character array.
I am having a few issues with my code. First: when I try to compile, I get error: too few arguments to function 'strcmp'. I have looked all over and made multiple changes and am still unable to get it to work. Second: when my code does compile (if I remove the strcmp part), it will not complete the count functions correctly. Can anyone please assist? Thank you!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int count(char array[], int size);
int stringLen(char array[]);
int convert(char ch);
int value, n;
int main()
{
//char * str;
//char s;
char a[100];
char b[100];
char c[100];
int charCount = stringLen(a);
int lCount = count(a, charCount);
printf("Enter your string: \n");
scanf("%s \n", a);
printf("Enter your string: \n");
scanf("%s \n", b);
printf("Enter your string: \n");
scanf("%s \n", c);
printf("The count is %d, length is %d\n", lCount, charCount);
int i;
for(i = 0; i < charCount; i++)
{
char c = a[i];
printf("Char %s = %d \n", &c, value);
}
n = strcmp(char string1[], char string2[], char string3[]);
printf("The first string in the alphabet is: %d \n", n);
return 0;
}
int stringLen(char array[])
{
char count;
int index;
while(array[index] !=0)
{
count++;
index++;
}
return count;
}
int count(char array[], int size)
{
int count;
int i;
for(i = 0; i < size; i++)
{
if(array[i] == 'a')
{
count ++;
}
else if(array[i] == 'A')
{
count ++;
}
}
return count;
}
This is not right way to use strcmp.
n = strcmp(char string1[], char string2[], char string3[]);
strcmp is used for compararison of string. See doc
int result = strcmp (string1,string2)
If strings are same, function will return 0.