How to input N amount of characters into string from each line of a text file? [closed] - c++

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 6 years ago.
Improve this question
Please, if you write code in your answer, write it as if you were using namespace std;. Otherwise it's difficult for me to read :)
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int a; // a is amount of lines in file
string word[100];
int main()
{
ifstream fd("file.txt");
fd >> a;
for(int i=0; i<a; i++)
{
//here goes the code which inputs, let's say, 20 first characters of a line into string array - word[i].
}
fd.close();
return 0;
}

I'd take into account that the file might have more than 100 lines (which would then exceed your word-array, and I'd also take into account that the file might be inconsistent concerning number of lines stated in a and actual number of lines. Given that, try the following:
string line;
int i;
for(i=0; getline(fd, line) && i<a && i < 100; i++) {
word[i] = line.substr(0,20);
}
// at this point, "i" will hold the number of items actually written to "word".

Related

trying to plus each element of the loop over the next element [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 yesterday.
Improve this question
i'm trying to plus each elemnt of the loop result over the next elemnt
Like if i have a loop it gives me the numbers between 1~5 so i need 1+2+3+4+5
I tried below code but it didn't work
#include <iostream>
using namespace std;
int main() {
for (int i =1; i <=50 ;i++){
cout<<i<<" ";
cout<<(i +=i)<<endl;
}
return 0;
}
The variable 'i' is sort of a "control" variable that maintains the count. You are adding 'i' to itself and not actually printing it. If you need to print characters like a '+' you need to use quotation marks, unless they are variables.
The code you probably want to use is -
#include <iostream>
using namespace std;
int main() {
int n = 5;
for (int i=1; i<n; i++){
cout<<i<<"+";
}
cout<<n<<endl;
return 0;
}
Or if you wanted the sum of all the elements, the statement 'i+=1' actually adds 'i' to itself, this is not good as 'i' is your iterator, or a control variable of some sort that maintains your count. You should not operate over it. You will need another variable to hold the sum as you loop through.
You probably want this in this situation -
#include <iostream>
using namespace std;
int main() {
int sum=0;
for(int i=1; i<=5; i++){
sum+=i;
}
cout<<sum<<endl;
return 0;
}

avoiding the spaces and lines while reading text file in c++ [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 4 years ago.
Improve this question
if I got in a text file numbers like this
1.1 55 20
50
77
I can assign the first number to variable but cant read the other values
You can read the other values, if you continue reading data. For example:
std::vector<float> data;
float x;
while(std::cin >> x)
{
data.push_back(x);
}
Now you have a vector (see it as a normal array if you don't know what it is, or look at cppreference) which contains all the values you put in your text file.
you can try assigning them to array
#include <iostream>
#include <fstream>
using namespace std;
int main() {
double arr1[size];
ifstream input("file.txt");
for (int i = 0; i < size; i++) {
input >> arr1[i];
cout<< arr1[i]<<std::endl;
}
}

Hint: Missed newline ? while trying to solve the below quiz [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 8 years ago.
Improve this question
Problem
This is similar to the previous problem, however there will be multiple integers in the input. You have to write a computer program to read each integer and print Even if the integer is divisible by 2, else print Odd. To help further, the number of integers (T) to read will be the first input to the computer program.
Input Format:
First line of input contains count of integers: T. T>=1
After that, each line contains the integer N.
Sample Input:
2
4
5
Sample Output:
Even
Odd
Note: There should be a newline after each output. Otherwise you might end up printing EvenOdd here, which will result in wrong answer.
#include <iostream>
using namespace std;
int main()
{
int a[3];
cin>>a[0];
cin>>a[1];
cin>>a[2];
for(int i =0; i <sizeof(a)/sizeof(int); i++)
{
if (a[i]%2 == 0) cout<<"Even"<<endl;
else cout<<"Odd"<<endl;
}
return 0;
}
You don't need neither array nor vectors for this:
int main() {
int n;
cin >> n;
while(n--) {
int number;
cin >> number;
// do something with number
}
return 0;
}
Note that this structure is the most common to solve this kind of problems
your problem will be solved if you change
for(int i =0; i <sizeof(a)/sizeof(int); i++)
to
for(int i =1; i <sizeof(a)/sizeof(int); i++)
But, how'd you know the number of elemnts for the array beforehand?
To correct this, you don't declare the array statically. Take the first input, and allocate memory for that many ints.
#include <iostream>
using namespace std;
int main()
{
int a[3];
cin>>a[0];
cin>>a[1];
cin>>a[2];
for(int i =0; i <sizeof(a)/sizeof(int); i++)
{
if (a[i]%2 == 0)
cout<<"Even"<<endl;
else
cout<<"Odd"<<endl;
}
return 0;
}
this code which u posted is working perfectly bro :)

srand(time(NULL)) not giving strings anymore [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 9 years ago.
Improve this question
As a beginner in programming I can not find why srand would just not change the string anymore.
#include <stdlib.h>
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
int v[100], i, p, n,
srand(time(NULL));
cout<<"Numbers of numbers: "; cin>>n; cout<<endl;
for(i=0; i<=n-1; i++)
v[i]=rand()%100;
cout<<"Numbers: "<<endl;
for(i=0; i<=n-1; i++)
cout<<v[i]<<" ";
for(i=0; i<=(n-1)/2; i++){
p=v[i];
v[i]=v[n-(i+1)];
v[n-(i+1)]=p;
}
cout<<"Reversed numbers: "<<endl;
for(i=0; i<=n-1; i++)
cout<<v[i]<<" ";
return 0;
}
Tried rebuilding it, rewriting it from 1, and such. Even if it did work perfectly before it's just one type of bug that yeah, simply won't work.
Edit: Weird because I copy pasted the beginning and it worked with that... I guess it was my mistake. Not paying enough attention T_T
If you enable more warnings you will see something like
program.cpp:11:1: warning: unused variable 'srand' [-Wunused-variable]
srand(time(NULL));
^
The reason can be seen on the previous line: It ends in a comma
int v[100], i, p, n,
// Note comma here ^
So what the code is doing is declaring a variable named srand, and not calling a function called srand.
Take this as a lesson to always build with extra warnings enabled. Enabling more warnings made this problem very obvious, but it can also give hints about cases of undefined behavior.

Simple decoding program C++ [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 9 years ago.
Improve this question
I am doing a C++ course and middle way through the scholastic year we get a mock cw/exercise to do. it is not marked, it is only for practice.
basically, we have to do this
(a)Read text from a file and store its content in any array of
characters A. (b)Calculate the number and percentage of occurrences of
each letter in A using two parallel arrays (B and C): one containing
26 alphabet letters and the other containing their corresponding
percentage of occurrence. (c)Use a sorting algorithm (for example,
bubble sort algorithm) to sort the above two parallel arrays in
descending order of the percentage of occurrence. (d)Apply (b) and (c)
to the training and the encoded texts. Store both sets of parallel
arrays (for the training and the encoded texts) for further use.
(e)Use the above two sets of sorted parallel arrays to find and
display a one-to-one mapping of letters in the training and encoded
texts. (f)Substitutes the letters in the encoded message for letters
they represent (g)Ask interactively the user for a pair of characters,
store them in two character variables (for example, X and Y) and
substitute all occurrences of letter X for letter Y in an array of
characters. (h)Save the decoded text stored in an array of characters
to a file. (i)Be able to repeat (f), (g) and (h) as many times as the
user wishes.
We gotta do a procedural code first, then object oriented.
#include <fstream> //for file I/O
#include <iostream> //for cout, endl
#include <string> //for countletters
using namespace std;
int countletters(/*in*/ int& sum) //counting the number of letters contained in the file
{
string line;
ifstream inData ;
inData.open("encoded.txt");
while(!inData.eof())
{
getline(inData,line);
int numofChars= line.length();
for (unsigned int n = 0; n<line.length();n++)
{
if (line.at(n) == ' ')
{
numofChars--;
}
}
sum=numofChars+sum;
}
inData.close();
//sum is the number of letters inside the encoded.txt file
}
void fileintoarray(int& sum)
{
int arraysize = sum;
char myArray[arraysize];
char current_char;
int num_characters = 0;
int i = 0;
ifstream myfile ("encoded.txt");
if (myfile.is_open())
{
while (!myfile.eof())
{
myfile >> myArray[i];
i++;
num_characters ++;
}
for (int i = 0; i <= num_characters; i++)
{
cout << myArray[i];
}
system("pause");
}
}
int main()
{
int sum=0;
countletters();
fileintoarray();
return 0;
}
This is what I wrote so far, and the second function doesn't work.
It fails to compile.
Can anyone please help me on this one?
You are accessing the variable "sum" in your function "fileintoarray", but it's not in scope there as you declared it in "countletters".
Learn how to return values and how to pass parameters to functions - or, if you haven't learned that yet and are supposed to get along anyways - use global variables, because that's a little like the object-oriented version will be.