This is a C code to get a string for types of brackets '()' & '<>' & '{}' & '[]' from user. The length of this string is n and it is an user input.
int main()
{
long int n;
int i;
scanf("%lld", &n);
char array[n];
for(i=0; i<n ; i++)
{
scanf("%s", &array[i]);
}
}
The problem is I want to get the string without any spaces between them from user. But, this code is working for the input with space between each character and give the correct result.
For example, if I type {(() the program won't run. but if I type { ( ( ) the program shows the correct result.
How can I solve this problem?
Change:
scanf("%s", &array[i]);
to this:
scanf(" %c", &array[i]);
since what you attempt to do is read your string character by character.
Please notice the space before %c, which will consume the trailing newline that is going to be left in the stdin buffer from when you entered n.
I had wrote about the caution when reading a character with scanf() here.
Now, even if you use {(() or { ( ( ) for the input, it will be the same, since scanf() will ignore the whitespaces.
However, you should null terminate your string, if you want it to be used by standard functions, which you almost certainly want. For example, if you were to use printf("%s", array);, then you must have array null terminated.
An approach to this, assuming that the user will input correctly (in a perfect world), you could do that:
#include <stdio.h>
int main()
{
long int n;
int i;
scanf("%ld", &n);
// create an extra cell to store the null terminating character
char array[n + 1];
// read the 'n' characters of the user
for(i=0; i<n ; i++)
{
scanf(" %c", &array[i]);
}
// null terminate the string
array[n] = '\0';
// now all standard functions can be used by your string
printf("%s\n", array);
return 0;
}
PS: scanf("%lld", &n); --> scanf("%ld", &n);. Use your compiler's warnings! It will tell you about it..
If you want to make sure the user types at least 1 space character between each 'valid' character, you can just wait in the loop until the user adds a space character.
char c;
for (i = 0; i < n; i++)
{
c = '\0';
while (c != ' ') // wait for the user to type a space character
{
scanf ("%s", &c);
}
while (c == ' ') // wait for the user to type something else
{
scanf ("%s", &c);
}
array[i] = c;
}
Related
Is there a simple way to make sure you're reading a character through scanf. If it were an integer I'd use a do while loop
do{
printf("enter a number");
fehler = scanf(" %d", &x);
getchar();
} while(fehler!=1);
But I'm not fully sure what to do if the input is meant to be a string. I know the alphabets are stored as ASCII values but the if constraints in the while statement don't seem to be working(unless I'm doing it wrong)
char * temp2;
temp2 = malloc(sizeof(string));
do{
printf("PLease enter a string: ");
scanf(" %s", temp2);
getchar();
} while(temp2 <= 'A' && temp2 <= 'z')
You can't compare a string to a single character. You have to loop through the entire string, checking every character.
#include <ctype.h>
int is_alphabetic(char *str) {
for (int i = 0; str[i]; i++) {
if (!isalpha(str[i])) {
return 0;
}
}
return 1;
}
...
do{
printf("Please enter an alphabetic string: ");
scanf(" %s", temp2);
getchar();
} while(!is_alphabetic(temp2));
You see printf and scanf work independently. Whatever you store be it a character or number is stored in form of a number. Now it depends on the printf function what it demands.
Eg.: If you store 'a' at a location, the number 97 is stored. Now if you print a number it prints 97 and if you demand a character it gives a.
#include <stdio.h>
int main()
{
int i = 97;
printf("%d \n", i);
printf("%c", i);
return 0;
}
See the results. Further char, int , long int are just data types which specify the number of bits that would be resrved for the inputs for the variable.
Execute this program and you'll understand:
#include <stdio.h>
int main()
{
int i;
for (i=97; i <=200 ; i++)
{
printf("%d %c,\t",i,i);
};
return 0;}
This will show you a nmber when printed as a number and then the SAME number read as character.
Note there are no markers in memory to store which type of data it is. It is straightforward stored as number.
scanf is absolutely the wrong tool for this. But if you want to read only alphabetic characters, you can do it easily enough with something like:
char s[32];
if( 1 == scanf(" %31[a-zA-Z]", s) ){ ... }
The %31[a-zA-Z] conversion specifier will match only the literal characters a thru z and A thru Z, and will only consume up to 31 characters of input. You must always use a field width modifier with %s or %[] conversion specifiers to avoid an overflow.
Ive got this program which im stuck with in which I am trying to receive the size of a string and following it, telling the user to input the letter by letter. Here is my code.
#include<stdio.h>
#include<stdlib.h>
int main(){
int size;
int i;
char letter;
printf("Your string's size is...?: ");
scanf("%d", &size);
char mystring[size] ;
for (i=0; i<size; i++){
printf("Write a letter: \n");
scanf("%c", &letter);
mystring[i] = letter;
}
printf("%s",mystring);
system("PAUSE");
return 0;
}
Thanks!
Two problems here.
First, the %c format specifier to scanf will read any character, including a newline. You need to put a space before it to absorb any newlines in the input buffer:
scanf(" %c", &letter);
Second, you don't null-terminate the string, nor do you leave enough space in the array to store the null terminator. Make the array one element larger, and add the null byte at the end:
char mystring[size+1];
for (i=0; i<size; i++){
...
}
mystring[size] = 0;
Two things:
First, you need to terminate the string with a \0-character. Otherwise, printf will result in undefined behaviour.
Second, note that scanf("%c",..) will probably consume a new line left in the buffer when a user presses "enter" after having entered a number (i.e. the size).
Write:
char mystring[size+1] ;
for (i=0; i<size; i++){
printf("Write a letter: \n");
scanf("%c", &letter);
if (i==0 && letter == '\n') {
i--;
continue;
}
mystring[i] = letter;
}
mystring[size] = '\0';
printf("%s",mystring);
I'm completely new to programming (1st term in uni) and I can't keep up with my lecturer. At the moment I'm stuck on this exercise (for much more time than I'm willing to admit). I've tried to find help on the internet (in this site and others as well), but I can't, since our lecturer has us use a very simple form of c. I'm not asking necessarily for a complete answer. I'd really appreaciate even some hints about where I'm on the wrong. I understand that it might be really simple for some, that the question might seem ignorant or stupid and I feel bad for not getting what's wrong, but I need to try to understand.
So, what I'm trying to do is use scanf and a do while loop so the user can input characters in an array. But I don't understand why the loop won't stop when the user presses ENTER. There's more to the code, but I'm trying to take it slowly, step by step. (I'm not allowed to use pointers and getchar etc).
#include <stdio.h>
main()
{
char a[50];
int i;
printf("Give max 50 characters\n");
i=0;
do
{
scanf("%c", &a[i]);
i=i+1;
}
while((i<=50) && (a[i-1]!='\0'));
for(i=0; i<50; i++)
printf("%c", a[i]);
}
There aren't any nul-terminated strings here, but only string arrays.
So, when pressing enter, a[i-1] is \n not \0 (scanf with %c as parameter doesn't nul-terminate the strings, and ENTER is just a non-nul character with code 10 AKA \n)
Then don't print the rest of the string because you'll get junk, just reuse i when printing the string back:
#include <stdio.h>
main()
{
char a[50];
int i;
printf("Give max 50 characters\n");
i=0;
do
{
scanf("%c", &a[i]);
i=i+1;
}
while((i<sizeof(a)) && (a[i-1]!='\n')); // \n not \0
int j;
for(j=0; j<i; j++) // stop at i
printf("%c", a[j]); // output is flushed when \n is printed
}
Also test with i<50 not i<=50 because a[50] is outside the array bounds (I've generalized to sizeof(a))
Here is another way you can do this.
#include <stdio.h>
// define Start
#define ARRAY_SIZE 50
// define End
// Function Prototypes Start
void array_reader(char array[]);
void array_printer(char array[]);
// Function Prototypes End
int main(void) {
char user_input[ARRAY_SIZE];
printf("Please enter some characters (50 max)!\n");
array_reader(user_input);
printf("Here is what you said:\n");
array_printer(user_input);
return 0;
}
// Scans in characters into an array. Stops scanning if
// 50 characters have been scanned in or if it reads a
// new line.
void array_reader(char array[]) {
scanf("%c", &array[0]);
int i = 0;
while (
(array[i] != '\n') &&
(i < ARRAY_SIZE)
) {
i++;
scanf("%c", &array[i]);
}
array[i + 1] = '\0';
}
// Prints out an array of characters until it reaches
// the null terminator
void array_printer(char array[]) {
int i = 0;
while (array[i] != '\0') {
printf("%c", array[i]);
i++;
}
}
You may try with this code:
#include <stdio.h>
main()
{
char a[50];
int i;
printf("Give max 50 characters\n");
i=0;
do {
scanf("%c", &a[i]);
i=i+1;
} while(i<50 && a[i-1] != '\n');
a[i] = 0;
for(i=0; a[i] != 0; i++)
printf("%c", a[i]);
}
The function scanf("%c", pointer) will read one character at a time and place it at the pointer location. You are looking for '\0', which is a valid string terminator, but the newline character you get when you press ENTER and that you should be looking for is '\n'.
Also, it is a good idea to terminate the string you have read by adding a '\0' at the end (really a zero). Then use it to stop printing or you may print the "rest" of the contents of an uninitialized char array.
I want to store "char data type values" in an array, but it doesn't work.
First, I tried using "gets"
but it gave me a run time error.
Code was like this
int tmp = 0;
char arr[100] = { 0, };
while (arr[tmp]!=NULL)
{
gets(arr[tmp]);
tmp++;
}
for (int rtmp = 0; rtmp < a; rtmp++)
printf("%s ", arr[rtmp]);
return 0;
In a second way, I was using "scanf", but I couldn't store "char data type(it should be more than one character like string)", but only one character was available.(I tried %s, but it doesn't work)
Plus, it doesn't print the last value of array.
int a = 0;
scanf("%d", &a); //determine how much I input values
int tmp = 0;
char arr[100] ={ 0 , };
for(tmp=0;tmp<a;tmp++)
{
scanf("%c ",arr[tmp]);
fflush(stdin);
}
for (int rtmp = 0; rtmp < a; rtmp++)
printf("%c ", arr[rtmp]);
return 0;
The most "identical" for me is
without notifying "a" values("a" means how much values I input)
and storing "char values" in array..
How can I solve this problem?
Thanks in advance! Your help is always appreciated :)
Array of char data type is called Sting. You can take a string's input using scanf() and gets(). But if you use scanf(), the string will be input by pressing Space-bar or Enter. But if you use gets(), input will be given only by pressing the Enter key.
Example 1:
char s[100];
scanf("%s", s);
Example 2:
char s[100];
gets(s);
Now, if you want to input every single character individually, you can do that also:
char s[100], c;
int n, i, j;
scanf("%d", &n);
getchar();
for(i=0; i<n; i++) {
scanf("%c", &s[i]);
}
s[i] = '\0';
Now look, I wrote a getchar() after scanf("%d", &n);, because when you press enter after inputting n, a new line character ('\n') is also taken as input in the character next to n. So you must do this in case like this.
One more thing, you can take input any string containing spaces using scanf() also. Just do this:
char s[100];
scanf("%[^\n]", s);
You can not enter the individual character by following snippet of code.
char arr[10] = {0};
//unsigned char ch;
unsigned int i = 0;
printf("Enter the array elements\n");
for(i = 0; i<10; i++)
{
scanf("%c", &arr[i]);
printf("i = %d and arr[%d] = %c\n", i, i, arr[i]);
}
The result of this snippet is as per this image. enter image description here
To avoid this issue, it is recommended to enter the character without new line charactoer '\n' or without pressing enter.
Or other method is to use the array as string and input the character by gets() like this snippet.
char s[100];
gets(s);
I'm trying to write a program that counts all the characters in a string. I originally had it, but then realized I can't count spaces. I can't see why this does not work.
for(m=0; z[m] != 0; m++) {
if(z[m] != ' ') {
charcount ++;
}
}
Any assistance appreciated.
Edit* Does it make a difference if the input(strings) are being scanned in like this? And yes, everything is initialized. I've tried printing what z[m] evaluates too and it isn't the actual value of the string at "m", I think this is the problem.
for(j=0; j<7; j++){
printf("Enter a string:\n");
scanf("%s", z);
for(m=0; z[m] != 0; m++){
if(z[m] != ' '){
charcount ++;
}
}
You need to initialize charcount. Other than that, it should work, provided that z is a zero-terminated array of characters and m is an int or similar. I would probably write just z[m] rather than z[m] != 0 (since !0 = true and 0 = false), but both work. There are more efficient ways of doing it (although these days I bet a compiler will handle converting this into a pointer-based loop for you).
Here's a complete, correct example with minimal edits:
const char * z = "testing one two three";
int m;
int charcount;
charcount = 0;
for(m=0; z[m]; m++) {
if(z[m] != ' ') {
charcount ++;
}
}
If you're using a String class of some kind rather than an old-fashioned C null-terminated array, you'll want to look at that class for how to loop through it.
All of the above also assumes you're dealing with ASCII strings. If you're dealing with UTF-encoded strings, you have to handle multi-byte characters.
Re your edit: It makes a big difference: scanf will stop on the first blank (I'd forgotten that). It might make an even bigger difference than that, though, if you're not declaring z correctly. (I'd also recommend using a field width when using scanf for reading strings [or avoiding scanf entirely]; otherwise, you have no control over the number of chars it will try to store, and so in theory, no buffer will ever be big enough to avoid an overflow. More here: http://www.crasseux.com/books/ctutorial/String-overflows-with-scanf.html)
You can use strlen()
I'd suggest using a while loop, and to use more meaningful variable names
m = textIndex
z = text
Something like this would work
while (text[textIndex] != 0x00)
{
textIndex++;
}
Instead of using scanf, try fgets like so:
char input[256];
fgets(input, sizeof(input), stdin);
fgets will read an entire line from a file. As such, passing stdin as the file handle will make it read from standard input, which in most cases will be bound to the console. One thing to watch out for, though, is that the string you get from fgets might include the newline character. Rather than explicitly checking your strings for inequality with the space character (' '), I suggest using the isspace function from ctype.h, which will check for various forms of whitespace (including a regular space and newline).
Here is a complete, runnable example:
#include <stdio.h>
#include <ctype.h>
int count_nonspace(const char* str)
{
int count = 0;
while(*str)
{
if(!isspace(*str++))
count++;
}
return count;
}
int main()
{
char input[256];
fgets(input, sizeof(input), stdin);
printf("%d\n", count_nonspace(input));
}
Yes, there is a difference on input-scan with scanf:
scanf("%s", z);
...
if(z[m] != ' '){
scanf("%s"...) always breaks at space-character, therefore your if ever is true. Better you use fgets to read from stdin,
#define MAXINPUT 80
char line[MAXINPUT];
for(j=0; j<7; j++) {
printf("Enter a string:\n");
if( fgets( line, 80, stdin ) )
{
char *c=line;
if( strchr(line,'\n') ) *strchr(line,'\n')=0;
while( *c )
{
if( *c!=' ' )
++charcount;
++c;
}
}
}
Or if you want WHITE -spaces then take
#include <ctype.h>
...
if( !isspace(*c) )
this seems to work for me, its a simple 30 line code that is in a loop and can detect the letter of choice for the chosen string/sentence/word the user has inputted.
#include <stdio.h>
#include <string.h>
int main(){
while(true){
char string[100];
char letter[100];
int count = 0;
printf("Enter a word/sentence:\n");
scanf(" %[^\n]s",string);
printf("Enter a letter:\n");
scanf(" %c",&letter); //when using scanf for a sentence/word or character, always include a space afterwards.
//Counts each character except space
for(int i = 0; i < strlen(string); i++) {
if(string[i] == letter[0]){
count++;
}
}
//Displays the total number of characters present in the given string
printf("Total number of characters in the string: %d\n", count);
printf("%s\n",string);
}
return 0;
}