Page 1 of 1

Posted: Wed Nov 21, 2001 3:22 pm
by junjieliang
Just some qns:

1. Can all C programs be compiled in C++?
2. How does one check for end-of-line? Let's say I want to read numbers until the end-of-line. How do I do it?
3. How efficient is the function strlen()? If it check character by character until the null character, then it is O(n). Is that how it works?

Posted: Wed Nov 21, 2001 5:11 pm
by arnsfelt
> 1. Can all C programs be compiled in C++?

no, but well-written code will.

> 2. How does one check for end-of-line? Let's say I want to read numbers until the end-of-line. How do I do it?

In C you might want to use strtok or somthing similar.

Or you could try to do something like this

Code: Select all

scanf("%*[ t]");
while (scanf("%d%*[ t]%[rn]",&i,tmp)==1) {
  /* use i here */  
}  
  /* use last i here */
however note that if the input contains blank lines, this will not work very well.

In C++ a much nicer solution is

Code: Select all

getline(cin,s);
istringstream is(s);
while (is >> i) {
  // use i here
}
> 3. How efficient is the function strlen()? If it check character by character until the null character, then it is O(n). Is that how it works?

How it works or which complexity it has, is not specified.

But an implementation has to check every character in the string, so it's Omega(n).

Kristoffer Hansen

Posted: Thu Nov 22, 2001 3:15 am
by Casimiro
About reading until the end of line, I
usualy do a gets(s) and then a sequence of
sscanf's in the string s. You can do
something like this, for reading a variable
number of integers:

gets(s);
for(i = 0; sscanf(s,"%d %[^n]",&num,
tail); i++, strcpy(s,tail));

Well, maybe something like this, but I think
one can get the idea! :smile:

And about strlen, there's no way you can
do this without scanning the string. One
thing you can do is to set some variable
to strlen and then use this variable. This
is usefull inside loops, like this:

for(len = strlen(s), i = 0; i < len; i++)
/* do your stuff here */



Best Regards, Casimiro.

Posted: Tue Dec 11, 2001 12:37 am
by chrismoh
Nearly all C code can be compiled in C++, except for those using arcane constructs.

I prefer gets and strtok to read until end of line.

e.g. (to read numbers in one line)

gets(buf);
b = strtok(buf," -,;:"); /* whatever */
while (b) {
some_variable = atoi(b);
b = strtok(NULL," -,;:");
}

strlen is slow. Use it once, and assign a variable to store the value of the length of the string.