Efficient way to count ints in line C/C++ [closed] - c++

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I've been tasked with solving a rather simple problem but I'm stuck on 1 thing
Given the following file structure:
4
124 123 145 152
1400
13 23 51 24 1412 5151 52512 12412...
...
I am supposed to do various tasks with data but before doing anything with it I have to check whether int in first line corresponds to number of ints in 2nd line (same for 3rd and 4th line)
The problem is the number of elements can reach up to 150 000 and int value is between (1;2 000 000) so using getline can be problematic (afaik) as it will be resource heavy.
Cin will ignore whitespaces and \n so I will never know when line ends
I can't modify the original file and I try to use as least resources as possible.

hm not sure if i understand the question completely but why dont you use getline to store the line that contains 1400 ints as a string. Afterwards using a istringstream make sure you read 1400 ints. Maybe something like this:
getline(cin, line);
while(iss >> n && i++ < numOfInts) {}
then outside make sure i == numOfInts.
This way you'll never actually be storing 1400 ints, you'll just keep overwriting the previous integer

You can create a custom function to take the integer values, Something like this:
int getints(){
int ctr = 0;
char ch;
int sign = 1, n=0;
while(ch!='\n'){
while(ch==' ' || ch=='\t')
ch = getchar();
if(ch=='-'){
sign = -1;
ch = getchar();
}
while(ch >= '0' && ch <= '9'){
n = n*10 + ch - '0';
ch = getchar();
}
n *= sign;
++ctr;
}
return ctr;
}
This function will return the number of integers scanned in a line. Just check it with the number of integers that are supposed in a line. It basically skips all whitespace characters and terminates input after newline is found.

Related

Check an Array String character value without extra variable [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
suppose I've this code:
string str[] = {"devil", "chandra"};
// check if str[0] has properly devil, character by character or not without extra variable
Now I want to check str[ 0 ]'s all character which is 'd','e','v','i','l' one by one without extra variable.
with extra variable code will be :
string n1 = "devil";
for(int i=0; i<1; i++){
string s1 = str[i]
for(int j=0; j<s1.size(); j++){
if(s1[i] == n[i]){
cout << s1[i] << " ";
}
}
Basically, I want O(n) loop where I can access all indexes string and among them all characters.
Like s[ i ] is "devil" and s[[i]] = 'd' something like this, Know it's not valid, but is there any way to do that??
Even I don't know is it a valid question or not!
I'm not sure why you would need an extra variable. If you need a conditional that checks that the first value in the array of strings is "devil", it shouldn't be anymore complicated than:
if (str[0] == "devil")
{
* Do things *
}
C++ can check a standard string all at once. You don't need to check each individual character if that's what you're thinking.
Keep in mind, this isn't going to account for situations where the string is not exactly the same. For instance, if str[0] has "Devil" instead of "devil", then the conditional will evaluate to false.

Count the number of elements in txt file [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have an assignment like this:
/*
- Read an input text file (.txt) contain one line to store an array of integer:
Input.txt
4 1 2 -100 -3 10 98 7
- Write SumList function to sum all integer data of the list
- Write a function to find the max of all integer data
- ...
*/
My question is how to count the number of numbers in the txt file to use
/for (int i = 0; i < N; i++), N is number of numbers in file/ for reading the file. Or is there any way else to read this file without initializing N?
Thank you!
Your real question is: how to read a file word by word.
I believe that you've known what file stream is, so here is the code:
fstream file("yourfile.txt", ios::in);
std::string word;
while (file >> word)
{
// convert word to int
}
Now the next question is: how to convert a string to int. I hope you can figure it out on your own --- http://www.cplusplus.com/reference/cstdlib/atoi/
Also, this would be easier: (Thanks to #Fei Xiang)
int i;
while (file >> i)
{
// do something
}

Fast Scan stdin to get integer not working

I have made this function in c++ to read inputs from stdin faster than cin for using in competitive programming judges.
inline int VReadNumber() {
int n = 0;
int ch = getchar_unlocked();
while(ch >= '0' && ch <= '9') {
n = (n<<3) + (n<<1) + ch - '0';
ch = getchar_unlocked();
}
return n; }
It works perfectly if all inputs are given without line breaks like
2
40 40
80
5
1 2 3 4 5
10
But it doesn't do well with line breaks in the inputs like
2
40 40
80
5
1 2 3 4 5
10
and only reads values till the line break, here until 80.
How can i make this work with line breaks? Also a usage example would be greatly appreciated.
Is it worth using this with all its "nuances" instead of scanf and such?
That's because an empty line means two consecutive non-digit (\n) characters. Your code can handle only one. Add another loop for consuming whitespace, ideally at the beginning of the function and leave the last non-digit character in the buffer.

how to condense a string of numbers [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
char *s = "1234560000000000078999";
unsigned int ss = strlen(s);
vector<int> num;
unsigned int i;
for (i=0;i<ss;i+=2)
{
num.push_back((s[i] - '0')*10 + (s[i+1] - '0'));
}
i'm trying to condense a string that only contains numbers and store it in a int vector
the idea is to take each couple of numbers int the string and combain them into one integer
the problem i had is with numbers that start with zero , for example 1107 only gets stored as 117 and 1100 as 110
the other problem i had is with even numbers ;
any sultions please
thank you
1107 does, indeed, get stored as 11 and 07. When you display the values, show two digits or you won't see the leading 0 on the 07. Same thing with 1100.
As to even numbers, yes, you have to look more carefully at the number of digits that you're dealing with. If ss is odd, start out by just storing the first digit. Then process the rest in pairs. So 117 would be stored as, essentially, 01 and 17.

Separating number input into units [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
I need to separate users input into units and store them in an array.
e.g if user enters 6547. Array will store {6,5,4,7} Using C++ on Linux
I would appreciate if you can help me with pseudocode or explain an algorithm.
I'm a beginner so please restrain from advising advanced function (and explain its use if you do) as we have studied basics so far
N.B| If such question has already been answered and I skipped it in search, please do point me to it.
The math for isolating right most digit:
digit = digit % 10;
The math for shifting a number right by one digit:
new_number = old_number / 10;
Every letter and number can be represented as a text character. For example, '5' is a character representing the single decimal digit 5.
The math for converting a textual digit (character) to numeric:
digit = char_digit - '0';
Example:
digit = '9' - '0';
The math for converting a numeric digit to a textual digit (character):
char_digit = digit + '0';
Example:
char_digit = 5 + '0';
Your problem basically breaks into few parts, which you need to figure out:
how to read one character from input
how to convert one character to the digit it represents
how to store it in the array
Please, try to explain if you have problem with some particular point from the list above or there is a problem somewhere else.
Suppose Variable input_string holds the number entered by the user & you want to store it in an array named 'a'...Here's a C snippet.. you can easily convert it into C++ code..
I would recommend taking the input as string rather than int so that you can directly insert the digits extracted from the end...(else you can start storing the integer from beginning and then reverse the array)
scanf("%s",&input_string)
size = strlen(input_string)-1
input = atoi(input_string)
while (input/10>0)
{
i=input%10;
input=input/10;
a[size]=i;
size--;
}
Hope that helps!
Here's a C++11 solution:
std::string input;
std::cin >> input;
int num = std::stoi(input);
std::vector<int> v_int;
for (unsigned int i = 0; i < input.size(); i++)
{
v_int.push_back(num % 10);
num /= 10;
}
// To get the numbers in the original order
std::sort(v_int.rbegin(), v_int.rend());
for (unsigned int i = 0; i < v_int.size(); i++) {
std::cout << v_int[i] << std::endl;
}
If you want it in a c-style array, do this:
int* dynamic_array = new int[v_int.size()];
std::copy(v_int.begin(), v_int.end(), dynamic_array);
delete dynamic_array;