Clarifications

Write here if you have problems with your C source code

Moderator: Board moderators

Post Reply
junjieliang
Experienced poster
Posts: 169
Joined: Wed Oct 31, 2001 2:00 am
Location: Singapore

Post 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?

arnsfelt
New poster
Posts: 44
Joined: Wed Oct 17, 2001 2:00 am
Location: Denmark
Contact:

Post 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

Casimiro
New poster
Posts: 3
Joined: Thu Oct 18, 2001 2:00 am
Location: Rio de Janeiro, Brasil
Contact:

Post 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.

chrismoh
New poster
Posts: 35
Joined: Mon Dec 10, 2001 2:00 am
Location: Singapore; Cambridge, MA

Post 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.

Post Reply

Return to “C”