Why isn't this C code's \t working? - c

I am trying to print a pattern of numbers. Try running this code with a input of 20, you will see that the tab spaces are all in the wrong place, they don't follow the order. I know that the tab spaces jump to the next header, but is there a way to avoid it?
#include <stdio.h>
int main()
{
int i, n, count = 0;
scanf("%d", &n);
for(i = 1; i <= n; i++)
{
printf("%dnumber\t", i);
count++;
if(count == 4)
{
count = 0;
printf("\n");
}
}
return 0;
}
Note: Is there a way to do this with tab spaces only(i.e., "\t" only) instead of using an ordinary white space.
Here is the output that I am getting.
But what I want is this

There are several different problems here.
But it sounds like your main question is "gee: the tabs don't line up like I expect."
SUGGESTED ALTERNATIVE:
Consider using "field length specifiers" in printf():
http://www.cplusplus.com/reference/cstdio/printf/
EXAMPLE:
printf ("%-20s", mystring); // Will always be exactly 20 characters
printf ("%06d", myint); // 6-digits, zero filled

Why not:
#include <stdio.h>
int main( void )
{
int i = 0;
int n = 0;
scanf( "%d", &n );
for( i = 1; i <= n; i++ )
{
printf( "%02dnumber\t", i );
if( i % 4 == 0 )
printf("\n");
}
return 0;
}
Output:
16
01number 02number 03number 04number
05number 06number 07number 08number
09number 10number 11number 12number
13number 14number 15number 16number
Hope it helps!

Related

C, reading multiple numbers from a single line ignoring the whitespaces

I am working on a problem where I need to input a line of numbers with one or more whitespaces in between and add the numbers. But I am having a problem with ignoring the whitespaces.
I have tried using scanf(" ") and scanf("%*c").
What is the most efficient way to do so?
Thanks.
If the number of input integers in an entered string is unknown then you can use the approach shown in the demonstrative program.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
enum { N = 100 };
char line[N];
while ( fgets( line, N , stdin ) != NULL && line[0] != '\n' && line[0] != '\0' )
{
long long int sum = 0;
const char *s = line;
char *p = line;
do
{
s = p;
sum += strtol( s, &p, 10 );
} while ( s != p );
printf( "sum = %lld\n", sum );
}
return 0;
}
If to enter string
1 2 3 4 5
then the output will be
sum = 15
To read integers, use the format string %d, like this:
#include <stdio.h>
int main(void)
{
int sum, i, n;
sum = 0;
n = scanf("%d", &i);
while (n == 1) {
sum += i;
n = scanf("%d", &i);
}
printf("%d\n", sum);
return 0;
}
If you want to read real numbers, use the format string %lf (which stands for long float) and adjust the code above accordingly.
The way to do it in C++ would be
double a;
double b;
double c;
std::cin >> a >> b >> c;
I am not sure if you can do something very similar in C, please tell me if that was helpful.

Can you lend me a hand with this word counting code?

This code don't count words properly. I don't know if it is wrong on the for or what. Need help.
#include <stdio.h>
#include <stdlib.h>
int count_p(char sentence[100]) {
int i, m = 1;
for (i = 0 ; i < 100 ; i++) {
if (sentence[i] == ' ') {
m += 1;
}
}
return(m);
}
void main() {
char s[100];
int p;
printf("Sentence here: ");
scanf("%s", &s[50]);
p = count_p(sentence);
printf("Words: %d", p);
printf("\n");
}
The %s in scanf stops reading when it found a whitespace. Therefore, ' ' won't appear in s unless it was there as indeterminate value in uninitialized variable.
You can use fgets to read a whole line.
Here is a fixed code that also checks for end of the string.
#include <stdio.h>
#include <stdlib.h>
int count_p(char sentence[100]) {
int i, m = 1;
for (i = 0 ; i < 100 && sentence[i] != '\0'; i++) {
if (sentence[i] == ' ') {
m += 1;
}
}
return(m);
}
int main(void) {
char s[100];
int p;
printf("Sentence here: ");
fgets(s, sizeof(s), stdin);
p = count_p(s);
printf("Words: %d", p);
printf("\n");
return 0;
}
scanf("%s", &s[50]);
Not a correct way to take input and writing at index which is out of bound. Do this instead -
scanf("%99[^\n]", s); // this will read 99 characters and until '\n' is encountered
In main you function call is incorrect -
p = count_p(sentence); // sentence is not declares in main
Call like this -
p = count_p(s); // pass s instead of sentence to function
Also in function count_p change ccondition in for loop as -
size_t i;
size_t len=strlen(s);
for (i = 0 ; i < len ; i++)
You see &s[50] means that you pass a pointer to the 51-th element of s, you then try to access s from the beginning but, the first 50 characters in s were not yet initialized, this leads to undefined behavior.
Also, your loop from 0 to 99 will have the same issue since you might input a string of less than 100 characters, in that case you would be accessing uninitialized data too.
You can fix your program by changing this
scanf("%s", &s[50]);
to
scanf("%99s", s);
and then
for (i = 0 ; i < 100 ; i++) {
to
for (i = 0 ; s[i] != '\0' ; i++) {
because scanf() will append a '\0' to make the array a valid c string, that's also the reason for the "%99s".
Another problem is that, if you want white space characters not to make scanf() stop reading, you need a different specifier, because "%s" stops at the first white space character, this is a suggestion
scanf("%99[^\n]", s);
Or you can do as #MikeCAT suggested and go with fgets(). But be careful with the trailing '\n' in case of fgets().
And finally, altough highly unlikely in this situation, scanf() might fail. To indicate success it returns the number of specifiers actually matched, thus it might indicate partial success too. It's fairly common to see the return value of scanf() ignored, and it's very bad when you have a "%d" specifier for example because then the correspoinding parameter might be accessed before initializing it.
The statement scanf("%s", &s[50]); is in correct in your situation.Since you want to enter a sentence separated by spaces,the correct way of doing it is :
scanf(" %99[^\n]s",sentence);
That will prevent buffer overflow and allow space between words.Also your program does not seem to count words correctly if the sentence has consecutive whitespaces.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int count_p(char *sentence);
void main()
{
char sentence[100];
printf("Sentence here: ");
scanf(" %99[^\n]s",sentence);
int p = count_p(sentence);
printf("Words: %d", p);
printf("\n");
}
int count_p(char *sentence)
{
int len = strlen(sentence);
int x = 0 , wordCount = 0;
for( int n = 0 ; n < len ; n++ )
{
x++;
if( sentence[n] == ' ' )
x = 0;
if( x == 1 )
wordCount++;
}
return wordCount;
}

How can I print multiple character with one printf?

I want to print multiple character using printf. My approach up to now is this-
#include <stdio.h>
int main()
{
printf("%*c\n", 10, '#');
return 0;
}
But this only prints 9 spaces before the #.
I want to print it like this-
##########
I am unable to figure out how to do this. Please help me?
You can not use printf like that to print repetitive characters in Ansi C. I suggest you to use a loop like this -
#include <stdio.h>
int main()
{
int i;
for(i = 0; i < 10; i++) putchar('#');
return 0;
}
Or if you have absolutely no desire to use loops, you can do something like this-
#include <stdio.h>
int main()
{
char out[100];
memset(out, '#', 10);
out[10] = 0;
printf("%s", out);
return 0;
}
By the way, using printf like this also works-
#include <stdio.h>
int main()
{
printf("%.*s", 10, "############################################");
return 0;
}
I think the best approach, if you have an upper limit to the number of characters to be output is:
printf("%.*s", number_of_asterisks_to_be_printed,
"**********************************************************************");
I think this will also be the most efficient, portable way to do that.
this will print ten # characters, followed by a newline
char tenPounds[] = "##########";
printf( "%s\n", tenPounds);
I am working on a similar problem in "The C Programming Language" book (exercises 1-13 and 1-14). My own program, to start simply, is to count the occurrences of the digits 0 to 9 in a given input, and print a horizontal histogram made of '=' bars according to each count.
To do this, I created the following program;
main() {
int c, ix, k;
int nDigit[10];
//Instantiate zero values for nDigits array
for(ix = 0; ix < 10; ix++) {
nDigit[ix] = 0;
}
//Pull in input, counting digit occurrences and
//incrementing the corresponding value in the nDigit array
while ((c = getchar()) != EOF) {
if (c >= '0' && c <= '9') {
++nDigit[c-'0'];
}
}
//For each digit value in the array, print that many
//'=' symbols, then a new line when completed
for (ix = 0; ix < 10; ix++) {
k = 0;
while (k <= nDigit[ix]) {
putchar('=');
k++;
}
printf("\n");
}
}
Note that this is a work in progress. A proper histogram should include axes labels, and most importantly this program does not account for digits of zero count. If the input includes five 1's but no 0's, there is no visual way to show that we have no zeros. Still, the mechanism for printing multiple symbols works.

Using command line in C to detect arguments, and then print out the first or second char of the arguments

I need to make a program that accepts no less than 2 and no more than 6 arguments at the command line and then prints out the 1st or 2nd character
EX: asdf asdf asdf asdf
prints out as: a s a s
I have the initial array setup and working, the for loops below are meant to cut the string off at a space in the input and copy it to a new string, but it is not working correctly. I am new to C, and to this site. Any help is greatly appreciated.
#include <stdio.h>
#include <string.h>
int main(){
char a[50];
char b[50];
char c[50];
char d[50];
char e[50];
char f[50];
int i;
printf("enter a string (Ex: asdf asdf asdf... Must have atleast 2 arguments but no more than six): ");
scanf("%s", a);
printf("%c", a);
for (i = 0; i != 50; i++){
if(a[i]==' '){
char strncpy(b, &a[i], i+2);
printf("\n%c ",a[1]);
printf("%c ",b[0]);
}
}
for (i = 0; i != 50; i++){
if(b[i]==' '){
char strncpy(c, &b[i], i+2);
printf("%c ",c[1]);
}
}
for (i = 0; i != 50; i++){
if(c[i]==' '){
char strncpy(d, &c[i], i+2);
printf("%c ",d[0]);
}
}
for (i = 0; i != 50; i++){
if(d[i]==' '){
char strncpy(e, &d[i], i+2);
printf("%c ",e[1]);
}
}
for (i = 0; i != 50; i++){
if(e[i]==' '){
char strncpy(f, &e[i], i+2);
printf("%c ",f[0]);
}
}
return 0;
}
You don't need to copy your strings out of anywhere... Coming from the command line you'll have them sitting in argv:
int main( int argc, char **argv )
{
}
Where argc is the total number of arguments plus 1 (the first is the name that invoked your program), and argv is an array of pointers to each argument string. These have already been tokenised from the command-line.
So first you wanna test you have enough arguments. I like to explicitly make a new variable to remove the off-by-one confusion from comparisons:
int nparams = argc - 1;
if( nparams < 2 || nparams > 6 ) {
printf( "Wrong number of arguments\n" );
return -1;
}
Then you loop over your arguments. The first will be in position 1 of the array... From your example, it seems that you print the first character of the first argument, and the second character of the next, then continue alternating. That's a modulo operation. I have a variable which that chooses which character to print.
int i, which;
for( i = 1; i <= nparams; i++ ) {
which = (i-1) % 2;
printf( "%c\n", argv[i][which] );
}
This does assume that every second argument is at least two characters long. No error checking. If you need error checking, you need to make sure that the character you're printing is not the string-terminator (value 0). In the case of the second character, you also need to check the value before it is not 0. I don't know if it's possible to specify an argument that is a string of zero length. Perhaps a reader who does know can comment.
Well, I may as well put it in... So your loop would look a little like this:
if( argv[i][0] == 0 || argv[i][which] == 0 ) {
printf( "\n" );
} else {
printf( "%c\n", argv[i][which] );
}

How to read numbers separated by space using scanf

I want to read numbers(integer type) separated by spaces using scanf() function.
I have read the following:
C, reading multiple numbers from single input line (scanf?)
how to read scanf with spaces
It doesn't help me much.
How can I read numbers with space as delimiter. For e.g. I have following numbers as input 2 5 7 4 3 8 18 now I want to store these in different variables.
Please help.
I think by default values read by scanf with space/enter. Well you can provide space between '%d' if you are printing integers. Also same for other cases.
scanf("%d %d %d", &var1, &var2, &var3);
Similarly if you want to read comma separated values use :
scanf("%d,%d,%d", &var1, &var2, &var3);
scanf uses any whitespace as a delimiter, so if you just say scanf("%d", &var) it will skip any whitespace and then read an integer (digits up to the next non-digit) and nothing more.
Note that whitespace is any whitespace -- spaces, tabs, newlines, or carriage returns. Any of those are whitespace and any one or more of them will serve to delimit successive integers.
int main()
{
char string[200];
int g,a,i,G[20],A[20],met;
gets(string);
g=convert_input(G,string);
for(i=0;i<=g;i++)
printf("\n%d>>%d",i,G[i]);
return 0;
}
int convert_input(int K[],char string[200])
{
int j=0,i=0,temp=0;
while(string[i]!='\0')
{
temp=0;
while(string[i]!=' ' && string[i]!='\0')
temp=temp*10 + (string[i++]-'0') ;
if(string[i]==' ')
i++;
K[j++]=temp;
}
return j-1;
}
It should be as simple as using a list of receiving variables:
scanf("%i %i %i", &var1, &var2, &var3);
With this solution, it's possible to read positive and negatives integers:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER_SIZE 50
int convert_input (int * v, char * buffer) {
int len = 0, i = 0, temp = 0, positive_or_negative_one = 1;
while(buffer[i]!='\0') {
temp = 0;
if (buffer[i] == '-'){
positive_or_negative_one = -1;
i++;
} else {
while(buffer[i] != ' ' && buffer[i] != '\0')
temp = temp*10 + (buffer[i++]-'0');
if(buffer[i]==' ')
i++;
v[len++] = temp * positive_or_negative_one;
positive_or_negative_one = 1;
}
}
return len;
}
int main(int argc, char const *argv[]) {
int *a = NULL;
int count_a, len=0;
char buffer[BUFFER_SIZE];
printf("Input numbers here: ");
gets(buffer);
for (int i = 0; i < strlen(buffer); i++) {
if (buffer[i] == ' '){
len+=1;
}
}
a = (int*) malloc(sizeof(int) * len + 1);
count_a = convert_input(a, buffer);
for (int i = 0; i < count_a; i++) {
printf("%d\n", a[i]);
}
free(a);
return 0;
}
Input and output example:
Input numbers here: 1 2 3 -4 10
1
2
3
-4
10

Resources