The below code is not reading the correct chars from the file. Any idea what is wrong?
ifstream inFile;
inFile.open("chars.txt");
char ch; //dummy variable
char first, last;
int first1, last1;
for(int i=0;i<SIZE;i++)
{
for(int j=0;j<5;j++){
inFile.get(first);
inFile.get(last);
at this point first and last are not the correct chars from the file. (on the first run through the loop) It is probably something simple, but I am really bad at this.
Thanks in advance.
You don't need to parse the numbers manually like that.
Instead of using the get function, I'd recommend using the extraction operator >>, like in the following example:
#include <vector>
#include <fstream>
#include <iostream>
int main()
{
std::vector<int> values;
std::ifstream inFile("chars.txt");
int temp;
// Read the values in one at a time:
while (inFile >> temp)
{
values.push_back(temp);
}
// Demonstrate that we got them all by printing them back out:
for (unsigned int i = 0; i < values.size(); ++i)
{
std::cout << "[" << i << "]: " << values[i] << std::endl;
}
}
I am not sure if this applies to C++, but I had this problem in C#.
I had to use Char.GetNumericValue(); on the character being read.
Sample code in C#:
int myInt;
char myChar = '5';
myInt = Char.GetNumericValue(myChar);
Console.WriteLine("My character as int: "+myInt.ToString());
Related
I want to delete characters of a string that are in a vector, starting from an index inputted by the user up until the end of that string. For example if in index 0, my vector has the string "hello" and index 1 has the string, "goodbye", I want to erase the characters "llo" in the first string and "dbye" in the second string. So the result will be "he" in index 0 and "goo" in index 1. In my code that I am posting, I did not add the part of getting input from the user for the index. But just pretend, it is index 4 and beyond. How would I do this? Thank you.
I tried putting a '\0' character at the index that I want to start the deletion at, but that does not work.
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
int maxSize;
cin >> maxSize;
string usrInput;
vector<string> myArray;
for(int i = 0; i < maxSize; i++)
{
cin >> usrInput;
myArray.push_back(usrInput);
}
myArray[0][4] = '\0';
cout << myArray[0];
return 0;
}
You can combine the std::string method substr with the standard algorithm std::for_each to apply your cutting function to all strings in the vector.
#include <algorithm> // std::for_each
std::cout << "cut at length: ";
if(size_t cutpoint; std::cin >> cutpoint) {
std::for_each(myArray.begin(), myArray.end(), [&cutpoint](std::string& str) {
str = str.substr(0, cutpoint);
});
}
the std::string class provides a method substr which do the job.
Example:
int main()
{
int maxSize;
cin >> maxSize;
string usrInput;
vector<string> myArray;
for(int i = 0; i < maxSize; i++)
{
cin >> usrInput;
myArray.push_back(usrInput);
}
for ( auto& s: myArray )
{
s = s.substr(0,4);
std::cout << s << std::endl;
}
return 0;
}
http://www.cplusplus.com/reference/string/string/substr/
or
https://en.cppreference.com/w/cpp/string/basic_string/substr
Or you may want use resize which let the resulting string to be at a fixed size, if needed, filled up by a char which you can add as parameter.
https://en.cppreference.com/w/cpp/string/basic_string/resize
What you did is simply replacing a character inside the string. So if you have a string "abcdef" you will get "abcd\0e" which is not what you expect. You can see that yourself by printing out each of the chars like this:
myArray[0][4]='\0';
for ( auto&c: myArray[0] )
{
std::cout << (int) c << std::endl;
}
If you print it as a c-string, the output looks like the string is shorted, but it is really not! This one looks well but is wrong:
myArray[0][4]='\0';
std::cout << myArray[0].c_str() << std::endl;
Why?:
Quite simple: std::cout uses for printing std::string a different method than for printing c-style strings.
If you know where you want to cut, this is why substr function exist. Its a method from string, look at the documentation http://www.cplusplus.com/reference/string/string/substr/.
Hope it helps.
I was trying to build a vector of strings.
Some of the strings also contain Spaces.
That's why I was using getline(cin,string_name).
My code looks like
for(int i=0;i<n;++i)
{
getline(cin, s);
vec.push_back(s);
}
When I was taking input
ADAM BOB JOHNSON
It stopped after taking two input words, and the vector contents displayed are
(HERE SPACE IS DISPLAYED)ADAM BOB
What does it mean.Is it taking NULL string as input for the first string ?
It will be really helpful if someone tells me how to take the strings and display it.Thanks.
Abhijit,
Your information is, obviously, not enough. Assuming that your code is written on C++, I made this test cpp:
#include <iostream>
#include <string>
#include <vector>
int main()
{
std::vector<std::string> vec;
std::string s;
int n = 1;
for(int i = 0; i < n; ++i)
{
getline(std::cin, s);
vec.push_back(s);
std::cout << vec.at(i) << std::endl;
}
return 0;
}
Compiled with g++ and fed it with "ADAM BOB JOHNSON" string on input. Everything worked as it planned and it output was exact same as input. So I can see no error in here.
Sorry, cannot make it a comment due to insufficient reputation so far.
UPD: Found the issue. getline first gets '\n', we left after '3' (which is needed for std::cin >> n;) hence, you just need to ignore one string. The code:
#include <iostream>
#include <vector>
#include <string>
int main()
{
int n;
std::cin >> n;
std::vector<std::string> vec;
std::string s;
std::getline(std::cin, s);
for(int i = 0; i < n; ++i)
{
std::getline(std::cin, s);
vec.push_back(s);
// std::cout << vec.at(i) << std::endl;
}
for(int i=0;i<n;++i){
std::cout << vec[i] <<" " << std::endl;
}
return 0;
}
works fine for me.
And yep, #pmaxim98 made it first, sorry, was editing the reply and haven't seen your comment.
I'm trying to make a program that flips the words you input. The problem comes when I try to write the word and it asks twice for the input:
cin >> Arr >> myStr;
It is logical that it ask twice but everytime I try to use getline the compiler gives out an error (and even if it worked I have to give the input twice) and I need it to include spaces in the character array.
Here is my full code:
#include <iostream>
#include <string>
using namespace std;
string myStr;
string newVal;
int i;
int main()
{
char Arr[i];
cout << "Enter: ";
cin >> Arr >> myStr;
for (i = myStr.length(); i >= 0; i--)
{
cout << Arr[i];
}
cout << endl;
return 0;
}
The loop works.
The first problem can be corrected by achieving the proper use of getline.
The second one, I have got no idea (use a single input to assign two variables).
Thanks in advance, and I apologise if this is too much of a ridiculous question.
Maybe you can try to have a look to this solution that it's more C++ style than yours:
#include <iostream>
#include <string>
int main() {
std::string myStr;
std::cout << "Please give me a string: ";
if(std::getline(std::cin, myStr)) {
for(std::string::reverse_iterator it = myStr.rbegin();
it != myStr.rend();
++it) {
std::cout << *it;
}
std::cout << std::endl;
}
}
I suggest to you to use always std::string in C++ because has all the methods and function that you could need. So don't waste your time with char array like you do in C.
Here it is, as I said. I was digging around and came up with this:
#include <iostream>
#include <string>
using namespace std;
string myStr;
int i;
int main()
{
cout << "Enter: ";
getline (cin, myStr);
i = myStr.size();
cout << i << endl;
char Arr[i];
for (int a = 0; a <= i; a++)
{
Arr[a] = myStr[a];
}
for (i; i >= 0; i--)
{
cout << Arr[i];
}
return 0;
}
I did not know string contents could also have array-like behaviour. Test it out! Works like a charm (as far as tested).
The way I formatted the code it takes no more than 27 lines of code.
Thanks everyone involved, you helped me a lot.
P.S: Couldn't answer before, I can't do it soon enough with my reputation.
Let's say I have a file of names such as:
"erica","bosley","bob","david","janice"
That is, quotes around each name, each name separated by a comma with no space in between.
I want to read these into an array of strings, but can't seem to find the ignore/get/getline/whatever combo to work. I imagine this is a common problem but I'm trying to get better at file I/O and don't know much yet. Here's a basic version that just reads in the entire file as one string (NOT what I want, obviously):
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
fstream iFile("names.txt", ios::in);
string names[5];
int index = 0;
while(iFile)
{
iFile >> names[index];
index++;
}
for(int i = 0; i < 5; i++)
{
cout << "names[" << i << "]: " << names[i] << endl;
}
Output:
names[0]: "erica","bosley","bob","david","janice"
names[1]:
names[2]:
names[3]:
names[4]:
Also, I understand why it all gets read as a single string, but then why are the remaining elements not filled with garbage?
To be clear, I want the output to look like:
names[0]: erica
names[1]: bosley
names[2]: bob
names[3]: david
names[4]: janice
The easiest way to handle this:
Read the entire file and place it into a string, Here is an example of how to do it.
Split the string that you got from number 1. Here is an example of how to do that.
Stream extraction delimits by a space. Therefore the entire file gets read as one string. What you want instead is to split the string by commas.
#include <iostream>
#include <fstream>
#include <algorithm>
#include <sstream>
fstream iFile("names.txt", ios::in);
string file;
iFile >> file;
std::istringstream ss(file);
std::string token;
std::vector<std::string> names;
while(std::getline(ss, token, ',')) {
names.push_back(token);
}
To remove the quotes, use this code:
for (unsigned int i = 0; i < names.size(); i++) {
auto it = std::remove_if(names[i].begin(), names[i].end(), [&] (char c) { return c == '"'; });
names[i] = std::string(names[i].begin(), it);
}
remove_if returns the end iterator for the transformed string, which is why you construct the new string with (s.begin(), it).
Then output it:
for (unsigned int i = 0; i < names.size(); i++) {
std::cout << "names["<<i<<"]: " << names[i] << std::endl;
}
Live Example
I'm trying to read a list of numbers from a file and sort them by reading them into an array and then sorting the contents of the array. But I'm getting
error:incompatible types in assignment of 'std::basic_ostream<char, std::char_traits<char> >' to 'int [1]'
I'm fairly new to programming and this is my first time working with C++
Can anyone tell me how to write the list of numbers to an array so that I can sort them?
Here is what I have:
#include <fstream>
#include <iostream>
#include <iomanip>
#define ANYSIZE_ARRAY 1
using std::cout;
using std::endl;
int main()
{
const char* filename = "test.txt";
std::ifstream inputFile(filename);
int numbers[ANYSIZE_ARRAY];
int i, key;
// Make sure the file exists
if(!inputFile)
{
cout << endl << "The File is corrupt or does not exist. " << filename;
return 1;
}
long n = 0;
while(!inputFile.eof())
{
inputFile >> n;
numbers = cout << std::setw(10) << n;
}
for(int j=1;j<5;j++)
{
i=j-1;
key=numbers[j];
while(i>=0 && numbers[i]>key)
{
numbers[i+1]=numbers[i];
i--;
}
numbers[i+1]=key;
}
//Display sorted array
cout<<endl<<"Sorted Array\t";
for(i=0;i<5;i++)
cout<<numbers[i]<<"\t";
cout<<endl;
}
The line causing the error is:
numbers = cout << std::setw(10) << n;
I'm not quite sure what you're trying to do here, it looks like you just want to print it in which case the numbers = isn't needed.
The structure of your loop to read all the data is problematic also. The line: while (!inputFile.eof()) isn't idiomatic C++ and won't do what you hope. See here for a discussion on that issue (and here).
For reference you can do this quite simply with less work by using std::sort
#include <iterator>
#include <algorithm>
#include <vector>
#include <fstream>
#include <iostream>
int main() {
std::ifstream in("test.txt");
// Skip checking it
std::vector<int> numbers;
// Read all the ints from in:
std::copy(std::istream_iterator<int>(in), std::istream_iterator<int>(),
std::back_inserter(numbers));
// Sort the vector:
std::sort(numbers.begin(), numbers.end());
// Print the vector with tab separators:
std::copy(numbers.begin(), numbers.end(),
std::ostream_iterator<int>(std::cout, "\t"));
std::cout << std::endl;
}
This program also uses a std::vector instead of an array to abstract the "how big should my array be?" problem (which your example looked to have a possible problem problem with).
Here is what you need to do to get your program to work:
Change ANYSIZE_ARRAY to 5
Where you read the numbers, replace the while with this:
long n = 0;
i=0;
while(!inputFile.eof())
{
inputFile >> n;
cout << std::setw(10) << n;
numbers[i]=n;
i++;
}
This way, you will create an array which can hold 5 numbers, and you will read the numbers into that array. I used 5 because I saw that you were using the same number in the sorting algorithm, so I assumed that you only have to read 5 numbers. This is a bad thing, because your program will only work with 5 numbers.
If you need it to work with a variable amount of numbers, you can use a std::vector<long> to store the numbers. You can create a vector, and then use push_back() to add numbers to it. The vector will resize automatically and will hold as many numbers as you put in it. Then you can replace the 5s in your code with the vector's size() method.
You were getting your original error because this line doesn't make sense:
numbers = cout << std::setw(10) << n;
C++ views that line as if you are trying to print out the number to the stdout stream (which is in our case the console, the screen), and then assigning that stream to the "numbers" array. You cannot assign an output stream to an integer array (hence the error cannot convert from ostream to int[1]).
First, you should not assign an outstream variable to an int.
Second, n is long type and numbers is an integer array. There is type-unsafety.
Third, you should pre-allocate array size.
Forth, you can directly use sort() in STL function to do the sorting.
Try the following code:
#include <fstream>
#include <iostream>
#include <iomanip>
#include <algorithm>
using namespace std;
#define ANYSIZE_ARRAY 5
int main()
{
const char* filename = "test.txt";
std::ifstream inputFile(filename);
int numbers[ANYSIZE_ARRAY];
int i, key;
// Make sure the file exists
if(!inputFile)
{
cout << endl << "The File is corrupt or does not exist. " << filename;
return 1;
}
int n = 0;
i = 0;
while(!inputFile.eof())
{
inputFile >> n;
cout << std::setw(10) << n;
numbers[i++] = n;
}
sort(numbers, numbers + ANYSIZE_ARRAY);
//Display sorted array
cout<<endl<<"Sorted Array\t";
for(i=0; i<ANYSIZE_ARRAY; i++)
cout<<numbers[i]<<"\t";
cout<<endl;
}