This is only my third or fourth program so bear with me:
I have to write a program that reads string input until EOF and then prints the longest word + its length. I'm not supposed to use strlen(). This is the skeleton code that's been provided -
#include <stdio.h>
static const int max_word_len = 50;
int main(int argc, const char *argv[]){
int c = 0;
int i = 0;
int longest;
char current[max_word_len];
char longest[max_word_len];
while(... != EOF && i < max_word_len-1){
}
}
I then have to make use of this:
void copy(char src[], char dst[], int count);
I've no clue how to proceed so any help is appreciated.
Related
I'm doing an exercice where I need to split a string into an array of strings. The number of delimiters is checked before (the code snippet posted is a stripped down version however it doesn't work too), then the string is transformed into lowercase and it gets split into 4 parts separated by the delimiter "-". Here's the code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX_USERNAME_LENGHT 256
#define NUMBER_OF_ELEMENTS 4
void StringToArrayOfStrings(char *string, char **string_array, char *delimiter);
void LowerString(char * string, int string_lenght);
int main() {
char string[MAX_USERNAME_LENGHT] = "Joseph-Lucy-Mike-Nick"; //Test string
char *string_array[NUMBER_OF_ELEMENTS]; //We need four elements
char delimiter[] = "-";
int counter = 0;
//LowerString(string, strlen(string));
//printf("%s", string);
StringToArrayOfStrings(string, string_array, delimiter);
//Print each element of the string array
for (counter = 0; counter < NUMBER_OF_ELEMENTS; counter++) {
printf("\n%s\n", string_array[counter]);
}
return 0;
}
void LowerString(char * string, int string_lenght) {
unsigned short int counter;
for (counter = 0; counter < string_lenght; counter++) {
string[counter] = tolower(string[counter]);
}
}
void StringToArrayOfStrings(char *string, char **string_array, char *delimiter) {
unsigned short int counter;
char *token;
token = strtok(string, delimiter);
while(token != NULL) {
string_array[counter++] = token;
token = strtok(NULL, delimiter);
}
}
I've been scratching my head for the past 2 hours and I wasn't able to fix it. This programs works only if the string is not printed or/and transformed in lowercase. The program crashes when entering the loop in StringToArrayOfStrings. Where's the problem?
Thanks.
I want to split a string by the comma and separate the first number in the string into its own new string, the rest of the string I want to keep together.
So far I have tried this by using strtok() and I can get the first number into its own string, but now I can't figure out how to keep the rest of the string together.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
char testStr[] = "1000,first,second,third,+abc";
char *uidStr;
char *restOfstr;
int n;
//This is wrong, I know, but I want to populate
//the rest of the string after the first comma
//into a single string without the UID.
uidStr = strtok(testStr, ",");
while (n < 5)
{
restOfstr = strtok(NULL, ",");
n++;
}
return 0;
}
strtok works fine, you have to keep in mind that it returns a pointer to each tokenized word so you need two pointers one for the first token and other for the rest of the string.
Demo
#include <stdio.h>
#include <string.h>
int main()
{
char testStr[] = "1000,first,second,third,+abc";
char *uidStr; //pointer to uid
char *restOfstr; //pointers to the rest of the string
uidStr = strtok(testStr, ","); //uid remains in testStr
restOfstr = strtok(NULL, "\n"); //rest of the string
puts(uidStr); //or puts(testStr) to print uid
puts(restOfstr); //print rest of the string
return 0;
}
If you want a more secure function you can use strtok_s.
You can use strchr to find the first comma in the string.
Then using strncpy to get the number in the string.
The complete code:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
char *str = "1000,first,second,third,+abc";
char *s = strchr(str, ',');
if(!s)
return -1;
char num[10];
strncpy(num, str, s-str);
num[s-str] = '\0';
int a = strtol(num, NULL, 10);
printf("num = %d\nthe remaining: %s\n", a, s+1);
return 0;
}
#include <string.h>
#include <stdio.h>
int main(int ac, char **av) {
while (--ac) {
char *p = *++av;
char *t = strtok(p, ",");
char *r = strtok(NULL,"");
printf("%s : %s\n", t, r);
}
return 0;
}
Note that the empty string "" passed to the second strtok means that it cannot find a deliminator, thus returns the rest of the string.
In addition to the excellent answers #mevets and #anastaciu have provided (I would go with these), this code will also work fine.
#include <string.h>
#include <stdio.h>
int main(int argc, char** argv) {
char _p[] = "1000,Hey,There";
char* str1 = strtok(_p, ",");
char* str2 = strtok(NULL, "");
return 0;
}
I have been trying for hours to try and make this work, but the result was always the same-error and program not responding.
This file represents chat history and I select the username from every line. Now I want to add them into an array, so that I can later on count them for example.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char* argv[])
{
char const* const fileName = argv[1];
FILE* file = fopen("beispielhafteGeschichte3", "r");
char line[256];
int i, j, k;
char new_array[15][30];
while (fgets(line, sizeof(line), file))
{
for (i=0; i<strlen(line); i++)
{
if (line[i-1]==']')
{
for(k=i; k<strlen(line); k++)
{
printf("%c", line[k]);
if (line[k+1]==':') break;
}
strncpy(new_array[i], line[k], 29); // ?????
printf("\n");
}
}
}
fclose(file);
return 0;
}
How to fix strncpy?
for (i=0; i<strlen(line); i++)
{
if (line[i-1]==']')
The first time through the loop, i will be zero and you'll attempt to access line[-1] which invokes undefined behaviour
line[k] is a char type, while the prototype for the strncpy function is:
char *strncpy(char *dest, const char *src, size_t n)
You should try edit your code like this:
strncpy(new_array[i], line+k, 29);
How to print the environment variables in C, but WITHOUT VALUES ?? Only variables.
int main(int argc, char **argv, char **envp)
{
while(*envp!=NULL) {
printf("%s\n", *envp);
envp++;
}
system("pause");
return 0;
}
Since environmental variables have format of NAME=value you need to display only part of string up to = character.
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char **argv, char **envp)
{
while(*envp!=NULL) {
char * len = strchr(*envp, '=');
if (len == NULL)
printf("%s\n", *envp);
else
printf("%.*s\n", len - *envp, *envp);
envp++;
}
system("pause");
return 0;
}
Ideone
Environment variables are of the form NAME=value. So, you can look for the first = sign and print only upto it to get only the names.
Is there a way to print a string of fixed size in reverse without using pointers?
#include<stdio.h>
main()
{
char buffer[10];
scanf("%s", buffer);
// need to print buffer in reverse without using pointers??
}
A lovely K&R function to reverse your string in-place before printing it, perhaps?
#include <stdio.h>
#include <string.h>
void strrev(char *s) {
int tmp, i, j;
for (i = 0, j = strlen(s) - 1; i < j; i++, j--) {
tmp = s[i];
s[i] = s[j];
s[j] = tmp;
}
}
int main(int argc, const char *argv[]) {
char buffer[10];
scanf("%s", buffer);
strrev(buffer);
printf("%s\n", buffer);
return 0;
}
#include<stdio.h>
main()
{
char buffer[10];
int n = scanf("%s", buffer);
// print the number of chars written to buffer
if (n != EOF) {
int len = strlen(buffer);
if (len <= 10) {
int i;
for (i = len - 1; i >= 0; i--)
printf("%c", buffer[i]);
}
}
}
Since [] is just syntactic sugar for pointers, here's a version that works completely without pointers, arrays or anything else, just one single int. You didn't say that the string has to be stored somehow. :) (Note that I use fgetc instead of a buffer and scanf).
[jkramer/sgi5k:.../c]# cat rev.c
#include <stdio.h>
#include <stdlib.h>
void read_print();
int main(void) {
fputs("Enter your string, yo! ", stdout);
read_print();
fputs("\nDone!\n", stdout);
return EXIT_SUCCESS;
}
void read_print() {
int c = fgetc(stdin);
if(c != EOF && c != '\n') {
read_print();
fputc(c, stdout);
}
}
[jkramer/sgi5k:.../c]# gcc -o rev rev.c -Wall -W -Os
[jkramer/sgi5k:.../c]# ./rev
Enter your string, yo! foobar
raboof
Done!
Here's a recursive way of doing it; technically, this is using a pointer, but I wouldn't go into language-lawyer mode with such simple tasks.
#include <stdio.h>
/* If you want it printed forward, or backward, or think of another way.. */
typedef enum {
FRONT = 1,
BACK,
} direction;
/* Technically still using a pointer...don't nitpick. */
void echo_string(char buffer[], size_t buflen, direction from)
{
/* An index into the buffer to echo, which will preserve
* its value across subsequent recursive calls.
*/
static size_t index = 0;
/* According to the specified direction, print from the front
* or the back of the buffer. Advance the index (a misnomer, I guess).
*/
if(from == FRONT) {
printf("%c", buffer[index++]);
}
else {
printf("%c", buffer[buflen - ++index]);
}
/* Are there any more characters to echo? Yes? Awesome! */
if(index != buflen) {
echo_string(buffer, buflen, from);
}
}
int main(int argc, char **argv)
{
char buffer[10];
scanf("%s", buffer);
/* Better strlen() than sizeof() here,
* but BEWARE! scanf() is DANGEROUS!
*/
echo_string(buffer, strlen(buffer), BACK);
return(0);
}
reverse(char c[], int len)
{
if( ! (len / 2))
return;
char t = c[0];
c[0] = c[len--];
c[len] = t;
reverse(c, len-1);
}
The error(s) is left as an exercise to the student.
As caf pointed out, we're still using pointers..!
Here's an other way to solve the problem (of reversing a string).
This code snippet (and probably most others) don't respect stuff like utf8. I think signines post demonstrating the K&R way was quite close to mine (:D) so I adapted mine to fit that example (and corrected some things..)
#include <stdio.h>
#include <string.h>
void strrev(char *s) {
size_t len = strlen(s) + 1;
size_t i, j;
for(i = 0; i < len / 2; i++) {
j = len-1 - i-1;
char tmp = s[j];
s[j] = s[i];
s[i] = tmp;
}
}
int main(int argc, const char *argv[]) {
char buffer[10];
scanf("%s", buffer); // Look out for an overflow ;)
strrev(buffer);
puts(buffer);
return(0);
}
You can use strrev to reverse a string.
#include <stdio.h>
#include <string.h>
main()
{
char buffer[10];
scanf("%s", buffer);
strrev(buffer);
printf("%s", buffer);
}
void outstrreverse(const char s[])
{
size_t l=strlen(s);
while( l && s!=&s[--l] )
putchar(s[l]);
if(s[0])
putchar(s[0]);
}
Because of the relationship between C strings, arrays, and pointers the exercise is rather shotty IMHO - the most idiomatic description of a "String" in C is represented by the char*, which is not an array. Your (the OPs) title and post differ in their definitions between string and char[fixed length].
The OP should read and understand this FAQ entry, and between that and the posts here: easily figure out a solution—as well as defend it to the teacher/judge if need be.
I'll comment on this: never use scanf("%s", buffer) to populate a fixed length string. If you must use scanf() to do it, please use a field width specifier: e.g. scanf("%9s", buffer); if buffer is an [10], you want a specifier of 9 because of how scanf fills the buffer: otherwise you must beware the dragons! You could also scanf by character and evade the issue with a loops bounds, but that would likely be less efficient.
#include <stdio.h>
#include <conio.h>
void reverse(char a[], int s, int sc );
void reverse(char a[], int s, int sc ){
if ((sc-s)<(s-1))
{
a[sc-s]^=a[s-1];
a[s-1]^=a[sc-s];
a[sc-s]^=a[s-1];
reverse (a, s-1, sc) ;
}
}
void main (){
char a[]="ABCDEFG";
reverse(a, 7, 7);
printf("%d",a);
getch(); //i just use it to freeze the screen
}