Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 C++ String Handling
Index -> Programming, C++ -> C++ Help
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
jrcdude




PostPosted: Mon Feb 21, 2011 12:30 am   Post subject: C++ String Handling

For this post I will be referring to the CCC 2010 Junior Problem 4 question.

For my implementation of receiving the data to process, I had to use some very hacky techniques. I would like to know what the proper way to do this would be.

Example:

string input = "7 3 4 6 4 5 7 5";
int out[10];

I did the follow:

(int)input.at(0) - 48 //results in number of integers following

loop through the string
if((int)input.at(x) != 32)
out[x] = (int)input.at(x) - 48

if(input.at(x+1) != 32)
out[x] *= 10
out[x] += (int)input.at(x + 1) - 48

So as you can see it gets messy with the (int) conversion, etc.

I know in Java it would be much better to simply use a tokenizer with a space as a delimiter, but how would one do something such as this easily in C++, or is there a better technique for input such as this.

Thanks,
Jason
Sponsor
Sponsor
Sponsor
sponsor
Tony




PostPosted: Mon Feb 21, 2011 12:46 am   Post subject: RE:C++ String Handling

Isn't the iostream library the first thing that is taught for C++ (it being necessary for Hello World)?

Quote:

McAwesome:/tmp $ cat test.cpp
#include <iostream>

int main(){
int num_inputs, num;

std::cin >> num_inputs;
for(int i=0; i < num_inputs; i++){
std::cin >> num;
std::cout << "lol: " << num << std::endl;
}
return 0;
}
McAwesome:/tmp $ g++ test.cpp
McAwesome:/tmp $ echo "7 3 4 6 4 5 7 5" | ./a.out
lol: 3
lol: 4
lol: 6
lol: 4
lol: 5
lol: 7
lol: 5
Latest from compsci.ca/blog: Tony's programming blog. DWITE - a programming contest.
jrcdude




PostPosted: Mon Feb 21, 2011 12:57 am   Post subject: RE:C++ String Handling

My god.. Must have missed that lesson that each space counts as a new input. Thanks a lot!
Display posts from previous:   
   Index -> Programming, C++ -> C++ Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 3 Posts ]
Jump to:   


Style:  
Search: