I'm having issues writing a C function that reads a string from STDIN, and returns the length of said string... Suggestions?
So, simply use strlen from the C standard library:
#include <string.h>
So the strlen() function is available. You just need to pass a char pointer, and it will return the string length:
size_t length = strlen( myStr );
Note that size_t is an integral type.
By the way, if you don't know about this function, you should really dig into the C library, and lear about the basic functions it provides.
#include <stdio.h>
#include <stdlib.h> // not totally necessary just for EXIT_SUCCESS
#include <string.h>
int main(int argc, char* argv[]) {
// check number of params
if (argc != 2) {
// argv[0] is name of exe
printf("usage: %s string", argv[0]);
// check length of first command line parameter
} else {
// strlen does the counting work for you
unsigned int length = strlen(argv[1]);
printf("Length is %d\n", length);
}
return EXIT_SUCCESS;
}
Related
When I was making my program I got an error type of thing called Segmentation Fault.
#include <cs50.h>
#include <string.h>
#include <stdio.h>
int main(int argc, string argv[])
{
char i = strlen(argv[2]);
if (argc == 2)
{
printf("%i %s %hhd", argc, argv[2], i);
}
}
I run this program using these commands
make substitution
and then
./substitution abcdefghijklmnopqrstuvwxyz
In this we have to add a 26 word key which in the above line is a to z.
Please help if you know to solve
If you invoke your program with:
./substitution abcdefghijklmnopqrstuvwxyz
argc will be 2, and argv will be an array of 3 pointers:
argv[0] points to the string ./substitution, argv[1] points to the string abcdefghijklmnopqrstuvwxyz, and argv[2] is NULL. If you attempt to compute the length of NULL by calling strlen(argv[2]), that is an error. You must not pass NULL to strlen. I think your error is simply mis-indexing the argv array. Arrays in C are zero based. If you want to compute the length of the first argument, you want to work with argv[1], not argv[2]:
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int
main(int argc, char *argv[])
{
int rc = EXIT_FAILURE;
if( argc > 1 ){
size_t i = strlen(argv[1]);
printf("%i %s %zd\n", argc, argv[1], i);
rc = EXIT_SUCCESS;
}
return rc;
}
You got hit with segfault because the number of required arguments specified was done poorly. The main problem is here:
if (argc == 2)
The number of actual arguments passed by the user is equal to the number of required arguments minus 11. It should be:
int main(int argc, char *argv[]) {
if (argc != 3) {
// Number of arguments are either greater or lesser than 3
// Handle the error
}
// Ok...
}
You can safely use the arguments now.
1. The calling command for the program, for example ./a.out is also counted as an argument (argv[0]).
I have been trying to get strcmp to return true in the following program for many days now, I have read the man pages for strcmp, read, write... I have other's posts who have had the exact same problem. The following source code is just a test program that is frustrating the heck out of me, there are some commented out lines that are other attempts I've made at getting strcmp to work as expected. I have compiled with 'gdb -g' and stepped through one instruction at a time. The printf statements pretty much tell the whole story. I cannot get the value of buf, or bufptr to equal 't' ever. I have simplified the program, and had it just print one character at a time one after the other to the screen and they print as expected from whatever file is read-in, however, as soon as I start playing with strcmp, things get crazy. I cannot for the life of me figure out a way to get the value in buf to be the single char that I am expecting it to be.
When simplified to just the write(1,...) call, it writes the expected single char to stdout, but strcmp to a single 't' never returns 0. !!!!! Thank you in advance. I originally didnt have bufptr in there and was doing a strcmp to buf itself and also tried using bufptr[0] = buf[0] and the still were not the same.
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#define BUF_SIZE 1
void main(int argc, char *argv[])
{
char buf[BUF_SIZE];
int inputFd = open(argv[1], O_RDONLY);
char tee[] = "t";
int fff = 999;
char bufptr[BUF_SIZE];
// char *bufptr[BUF_SIZE];
while (read(inputFd, buf, BUF_SIZE) > 0) {
bufptr[0] = buf[0];
// bufptr = buf;
printf("********STRCMP RETURNED->%d\n", fff); // for debugging purposes
printf("--------tee is -> %s\n", tee); // for debugging purposes
printf("++++++++buf is -> %s\n", buf); // " " "
printf("########bufptr is -> %s", bufptr); // " " "
write (1, buf, BUF_SIZE);
if ((fff = strcmp(tee, bufptr)) == 0)
printf("THIS CHARACTER IS A T");
}
close(inputFd);
}
The str-family of functions expects strings as inputs, which are arrays storing null-terminated character sequences. However, you do not provide space in the buffer for the null character. To make the buffers strings, you need to add space for the null-character and zero-out the value so that they end with the null character.
void main(int argc, char *argv[])
{
char buf[ BUF_SIZE + 1 ] = {0};
int inputFd = open(argv[1], O_RDONLY);
char tee[] = "t";
while (read(inputFd, buf, BUF_SIZE) > 0) {
if ( strcmp( tee, buf ) == 0 )
printf("THIS CHARACTER IS A T");
}
close(inputFd);
}
I want to parse an integer but my following code also accepts Strings like "3b" which start as a number but have appended chars. How do I reject such Strings?
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int n;
if(argc==2 && sscanf(argv[1], "%d", &n)==1 && n>0){
f(n);
return 0;
}
else{
exit(EXIT_FAILURE);
}
}
For your problem, you can use strtol() function from the #include <stdlib.h> library.
How to use strtol(Sample code from tutorial points)
#include <stdio.h>
#include <stdlib.h>
int main(){
char str[30] = "2030300 This is test";
char *ptr;
long ret;
ret = strtol(str, &ptr, 10);
printf("The number(unsigned long integer) is %ld\n", ret);
printf("String part is |%s|", ptr);
return(0);
}
Inside the strtol, it scans str, stores the words in a pointer, then the base of the number being converted. If the base is between 2 and 36, it is used as the radix of the number. But I recommend putting zero where the 10 is so it will automatically pick the right number. The rest is stored in ret.
The ctype.h library provides you the function isdigit(char) function that returns whether the char provided as argument is a digit or not.
You could iterate over argv[1] and check it this way.
I want to print a line similar as following:
====================================
And I need to control the count of the char, and able to specify which char to print.
I don't want to use loop.
Is it possible to do this with a single printf() statement?
#Update
I ask this because I use printf in this way sometimes:
printf("%10s\n", "abc");
So, if printf could do this, then it's possible to do what I ask, I am just not sure ... now I know it can't ...
Ok, I wrote a simple util function to do this:
#include <stdio.h>
void printRepeatChar(char c, int count) {
char cs[count+1];
int i;
for(i=0; i<count; i++)
cs[i] = c;
cs[count] = '\0';
printf("%s\n", cs);
}
int main(int argc, char * argv[]) {
printRepeatChar('-', 6*4);
}
maybe use memset() from string.h instead of the direct loop makes the code shorter, just as in the answers.
And, thank you all for help.
#include <stdio.h>
#include <string.h>
void PrintStuff( char to_print, int length ) {
// adjust buffer size as desired
char buffer[256];
// -1 for null terminator
if( length > sizeof(buffer)-1 ) length = sizeof(buffer)-1;
// fill buffer with desired character
memset( buffer, to_print, length );
// add null terminator
buffer[length] = 0;
// print to output
puts( buffer );
}
int main() {
PrintStuff( '=', 11 );
return 0;
}
http://ideone.com/RjPr83
And to answer the subquestion: no, printf cannot repeat a character as a formatting rule. It can only repeat spaces or 0's when padding.
#include <stdio.h>
#include <string.h>
int main(void) {
char c='=';
char a[20];
memset(a,c,(sizeof(a)-1));
a[19] = '\0';
printf("%s\n",a);
return 0;
}
Dynamic memory allocation and character scanning can be added to this .
Why does my code not accept the argv[] string? What do I need to do to fix it? I want to be able to type in both lower and upper case letters and end up with only lowercase letters in the array. Thanks for any help.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(int argc, char argv[])
{
char word[30]= atoi(argv[1]); // here is the input
for (int i = 0; word[i]; i++)
word[i] = tolower(word[i]);
printf("Here is the new word: %s\n", word);
return 0;
}
int main(int argc, char argv[])
should be:
int main(int argc, char *argv[])
Besides, strtol is a better option than atoi as strtol can handle failures better.
You have several problems with your code:
As KingsIndian already mentioned, you are missing a * in front of the argv paramter of the main function. This 'Main Function' wiki page contains some more details on this.
atoi is used to convert a string number to an integer number. This is not what you want I suppose. argv[x] is already a string (char *), so you can use it directly.
If you use it directly, you cannot modify it contents (not allowed, I believe). Therefore you need to make a copy. Use strlen() to find out the length of argv[1], malloc() to create an buffer and strcpy() to copy it:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int main(int argc, char *argv[])
{
char *word = malloc(strlen(argv[1]) + 1);
strcpy(word, argv[1]);
int i;
for (i = 0; word[i]; i++)
word[i] = tolower(word[i]);
printf("Here is the new word: %s\n", word);
return 0;
}
Additional notes:
It would be better (more robust) if you check the amount of given command line parameters using argc!
In theory malloc() can return 0, indicating that claiming the memory did fail. So you should check for this.
If you only want to print the lower case world, you do not require to first convert it and then print it. Instead, you could directly print each converted character.