I'm trying to pass a pointer array of strings to function toupper() in C.
main() {
char *choice[1];
scanf("%s", choice);
printf("%s", toupper(&choice[0]));
}
I always type in a lowercase word such as "modify" to test it. Different variations of this, such as toupper(*choice[0]) or toupper(*choice) or mixtures of them all, including &, have either thrown an error or returned the same lowercase "modify". Any suggestions?
To start with array of char pointers having one element doesn't make much sense to me since it will only point to one string.Why not declare a char array if you just want a single string?
Prototype of toupper is this:
int toupper( int ch );
It doesn't take an array.
You can try like this :
#include <stdio.h>
#include <ctype.h>
int main()
{
char str[25];
int i = 0;
setbuf(stdout,NULL);
printf ("enter the name \n");
fgets (str,sizeof str-1, stdin);
printf ("the name entered in upper case is :\n");
while (str[i])
{
int c = str[i];
printf ("%c",toupper(c));
i++;
}
return 0;
}
NOTE- Do not use scanf for taking strings try fgets , its better.
Before you call scanf, you need to allocate some space for the characters to be stored in. You only allocate a single pointer and then you don't even set it to point to anything. Similarly, toupper returns the converted character, which is not a string, so passing it to printf through %s is also wrong.
Something like this should serve the purpose.
#include<stdio.h>
#include<ctype.h>
void StrToUpper(char *str)
{
while(*str != '\0')
{
*str = toupper(*str);
str++;
}
}
int main()
{
char *choice[1];
choice[1] = new char[10];
scanf("%s", choice[1]);
StrToUpper(choice[1]);
printf("%s", choice[1]);
return 0;
}
In the program, you have array of pointers.
So:
Allocate memory for your string
call toupper(choice[0][0]);
toupper takes only a character value (between 0 and 255), not a pointer or array.
Related
The console will not do anything after the user has entered a string.
I have got the code to work using char string="enteraword" and taking out the whole printf and scanf function, however I need the code to work with a scanf function.
#include <stdio.h>
#include <string.h>
int main()
{
char* string;
printf("Enter a word: ");
scanf("%s", string);
char c=string[1];
printf("The second letter in %s is %c", string, c);
return 0;
}
This code has undefined behavior, you're passing an uninitialized pointer to scanf(), asking it to store a string there.
Also, remember that %s will stop at whitespace, so it's very unclear what "terms" should mean here.
Try e.g.:
char string[1024];
if(scanf("%1023s", string) == 1 && string[0] != '\0')
{
const char c = string[1];
printf("The second letter of '%s' is '%c'\n", string, c);
}
How can I check whether there are numbers in char provided by user in C language?
Last line of C code to change :):
char name;
do{
printf("What's your name?\n");
scanf("%s\n", name);
}
\\and here's my pseudocode:
while (name consist of a sign (0 or 1 or 2 or 3 or 4 or 5 or 6 or 7 or 8 or 9));
Here is a different approach that tests for specified chars in one function call.
#include <stdio.h>
#include <string.h>
int main()
{
char name[100];
char charset[]= "-+0123456789";
int len;
do {
printf("What's your name?\n");
scanf("%s", name);
len = strlen(name);
}
while (strcspn(name, charset) != len);
printf ("Your name is '%s'\n", name);
return 0;
}
You need to include ctype.h and use the isdigit() function.
But you also have another porblems in the posted code, "%s" specifier expects a char pointer, and you are passing a char, may be what you need is a char array like this
#include <stdio.h>
#include <ctype.h>
int main()
{
char name[100];
int i;
do {
printf("What's your name?\n");
scanf("%s\n", name);
}
/* and here's my pseudocode: */
i = 0;
while ((name[i] != '\0') &&
((isdigit(name[i]) != 0) || (name[i] == '-') || (name[i] == '+')))
{
/* do something here */
}
}
remember to include ctype.h and stdio.h
Use isdigit();
Prototype is:
int isdigit(int c);
Similarly to check the character is alphabet
Use
isalpha()
Once you get the string from the user, loop on it to search for correct input. (i.e. to see if there is a digit embedded in a collection of alpha characters). Something like this will work:
Assume userInput is your string:
int i, IsADigit=0;
int len = strlen(userInput);
for(i=0;i<len;i++)
{
IsADigit |= isdigit(userInput[i]);
}
The expression in the loop uses |=, which will detect and keep a TRUE value if any of the characters in the string are a digit.
There are many other methods that will work.
And the following family of character tests will allow you to do similar searches for other types of searches etc.:
isalnum(.) //alphanumeric test
isalpha(.) //alphabetic test
iscntrl(.) //control char test
isalnum(.) //decimal digit char test
isxdigit(.) //hex digit char test
islower(.) //lowercase char test
...The list goes on
This is code I wrote that checks if a string is a palindrome or not. I need to revise this code so that it uses character pointers in it. Could someone give me some suggestions/tips...or show me how to do that? Thanks
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(){
char string1[20];
int i, length;
int flag = 0;
printf("Enter a string: ");
scanf("%s", string1);
length = strlen(string1);
for(i=0;i < length ;i++){
if(toupper(string1[i]) != toupper(string1[length-i-1])){
flag = 1;
break;
}
}
if (flag)
printf("%s is not a palindrome \n\n", string1);
else
printf("%s is a palindrome \n", string1);
return 0;
}
In your code you use string1[i] to access the current element from the beginning of the string, and string1[length-i-1] to access the current element from the end of the string. You could create two pointers, pb and pe, and then move them toward each other.
To define pointers, use this:
char *pb = &string1[0]; // Or just string1, compiler will convert it to pointer
char *pe = &string1[length-1];
To advance the pointers toward each other, use pb++ and pe--.
To see if the pointers have not crossed each other , check that pb < pe. Currently, your program checks the string twice; there's no need to do that - you can stop as soon as pe becomes less than or equal to the pb.
To access the character pointed to by the current pointer, use
toupper(*pb) != toupper(*pe)
You can combine the check with advancing the pointers, like this:
toupper(*pb++) != toupper(*pe--)
Note: it is not safe to use %s, because when users enter more characters than fits in your string1 buffer overrun results. You should specify the length of the buffer, like this:
scanf("%19s", string1); // Leave one char for null terminator
I'm not sure I completely understand the question, but I think this answers it. You actually are using character pointers. char string1[20] is the same as char *string1. The difference is that you've basically assigned the pointer to a block of memory. You could access the string in this way.
char string[20] = "foo";
printf("%c\n", string[0]); // will print 'f'
printf("%c\n", *string); // will also print 'f'
printf("%c\n", string[1]); // will print the first 'o'
printf("%c\n", *(string + 1)); // will also print the first 'o'
with char * it goes like this
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main()
{
char string1[20];
int i, length;
int flag = 0;
printf("Enter a string: ");
scanf("%s", string1);
length = strlen(string1);
char *start=string1;
char *end=&string1[length-1];
//only check upto half
for(i=0;i <= (length-1)/2 ;i++)
{
if(toupper(*(start+i)) != toupper(*(end-i)))
{
flag = 1;
break;
}
}
if (flag)
printf("%s is not a palindrome \n\n", string1);
else
printf("%s is a palindrome \n", string1);
return 0;
}
cant we just copy the original string to another array, and then use strrev() to reverse the copied string and then finally compare the original string with the reversed string?
Like this
1.get new string
2.copy string to new array
3.reverse the copied string using strrev
4.use strcmp to check if both are same or not?
this seemed easier
(i am a beginner so please correct me if i am wrong)
I have a question simple like that: Let user enter some words from keyboard,one word per line until a '.' (period) entered then print out result, for example:
Enter a word: word1
Enter a word: word2
Enter a word: .
You have entered 2 word(s):
word1
word2
OK here my try but when I run it said file has stopped working after let me enter first word
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>
int main ()
{
char *word[50]; //each word has maximum 49 character
int i=0, number_of_word;
do
{
printf ("Enter a word: ");
scanf("%s", &word[i]);
i++;
}
while (word[i][0]!='.');
number_of_word =i;
printf ("You entered %d word(s):\n", number_of_word);
for (i=0; i<number_of_word; i++)
{
printf("%s\n", &word[i]);
}
return 0;
}
-----------------------------------------------------------------------
EDIT 1:
OK I try this, it worked but I am still looking for best way to declare an unknown size array of character string since I don't know neither how many word user may enter nor how many letter of each word, in C++ it may called dynamic allocation array, I have no idea how to do it in C
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>
int main ()
{
char word[20][50]; //array has maximum 20 words, each word maximum 50 character
int i=0, number_of_word;
do
{
printf ("Enter a word: ");
scanf("%s", word[i]);
i++;
}
while (word[i-1][0]!='.');
number_of_word =i-1;
printf ("You entered %d word(s):\n", number_of_word);
for (i=0; i<number_of_word; i++)
{
printf("Word %d is %s\n", i, word[i]);
}
return 0;
}
You are not assigning any memory to store the individual strings, so your program invokes undefined behaviour.
This:
char *word[50];
defines an array of 50 pointers, but no further storage.
And when you do this:
scanf("%s", &word[i]);
you're writing into the pointer array.
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>
int main () {
char *word[50]; //each word has maximum 50 word
char enter_word[50];//maximum 49 character
int i=0, number_of_word;
while(1){
printf("Enter a word: ");
scanf("%49s", enter_word);
if(*enter_word == '.')break;
word[i++]=strdup(enter_word);
}
number_of_word = i;
printf ("You entered %d word(s):\n", number_of_word);
for (i=0; i<number_of_word; i++){
printf("%s\n", word[i]);
}
for(i=0;i<number_of_word; ++i)
free(word[i]);
return 0;
}
When you declare
char *word[50];
You have 50 char pointers pointing to random memory. What you want is something like this:
char word[50][50];
Note that you can have only 49 words (and the '.'), and each can have less than 50 characters (don't forget the \0, so a word with 50 chars will overflow).
And you will want to change your scanf call to something like:
scanf("%s", word[i]);
Note that you do not need the &, since word[i] is already a pointer.
char *word[50];
You have an array of 50 pointers. You want an array of 50 byte chunks. How many words do you want to read? If you know the maximum, you can allocate the space in advance. If you don't, you need something like a linked list of strings, to which you can append a new item when you read it.
Its your printf Call. Remember to add the end character \0 to the end of the word. Printf when printing strings prints everything in the char array till it reads an end character \0
BasicAlly... Hos should printf know how long the word is and when it should stop printing?(Right now it continues forever)
You've done nothing to allocate memory for the individual strings.
Char *word[50] just declares a pointer to one array of char pointers.
EDIT
I'll try to illustrate this here with some pseudo code...formatted code on a phone is nearly impossible :) Given a prior char * input[50]:
char * nextString;
bool entering=true;
do{
nextString =calloc(50);
// enter the string to nextString
if (nextString[0] != '.'){
input[i] = nextString;
i++;
} else{
entering=false;
}
}
}while(entering)
"char *word[50]" have done nothing to allocate the memory for the individual string.
you should allocate it by using the function of alloc
you just try to use "%[^\n]" place of "%s" in scanf().
because "%s" stores characters until it found first space in the string.
try this with your very first asked Program
May its help to you.
I am refreshing my C skills and am having a little bit of difficulty with a simple program I am working on. Here it is:
#include <stdio.h>
#include <ctype.h> // for isdigit()
#include <stdlib.h> // for atoi()
int main (int argc, const char * argv[])
{
// first read in # of file events to follow, if not an int,
// complain & abort
char *input;
input = malloc(2); // input[0] holds the character
// input[1] holds the terminator
int numLines = 0;
scanf("%c", &input);
if (isdigit((int)input)) {
numLines = atoi(input);
} else {
printf("First line of input must be int type! Aborting...\n");
return 1;
}
//...
}
The problem is, then even when I enter a number (i.e. 2) it still outputs the aborting message and exits:
2
First line of input must be int type! Aborting...
I am having a hard time figuring out why it behaves like it is and what I should do to fix the problem. Shouldn't the '%c' specifier tell the compiler to take in the input as an ANSI character and then isdigit() should properly interpret that to be an integer?
Thanks in advance!
Change this:
scanf("%c", &input);
if (isdigit((int)input)) {
to this:
scanf("%c", input);
if (isdigit(input[0])) {
As it is right now, you are overwriting the pointer itself, rather writing to the allocated memory.
Also, you need to null-terminate:
input[1] = '\0';
Furthermore, it's not necessary to allocate memory for this. You can get away with just:
char input[] = " ";
scanf("%c", input);
if (isdigit(input[0])) {
numLines = atoi(input);
or alternatively:
char input;
scanf("%c", &input);
if (isdigit(input)) {
numLines = input - '0';
Change your code to:
char input[2] = {0}; // <<-- you don't clear the memory after malloc,
// your atoi might fail. No need for malloc here.
int numLines = 0;
scanf("%c", &input[0]);
if (isdigit((int)input[0])) {
numLines = atoi(input);
} else {
printf("First line of input must be int type! Aborting...\n");
return 1;
}
And you're good. No need to dynamically allocate here, its just a waste of effort.
When you pass &input to scanf, you are passing a pointer to a char *. You should just pass the pointer itself, that is,
scanf("%c", input);