C++ (SPOJ - POL-polowa) - problem with compilation - c++

I have problem with making correct code for this task in SPOJ https://pl.spoj.com/problems/POL/.
When I wrote all what I needed, program worked correctly. But when I tried to convert it in function, I have on ideone.com problem like this -> double free or corruption (out). Can anybody help me please ? What I am doing wrong ? I am beginner and I realize that can be very trivial.
#include <iostream>
using namespace std;
int polowa()
{
int t;
cin>>t;
string slowa[100]={};
string nowe_slowa[100]={};
for (int i=0;i<t;i++)
{
cin>>slowa[i];
}
for (int i=0;i<t;i++)
{
int k=slowa[i].length()/2;
nowe_slowa[i]=slowa[i].substr(0,k);
cout<<nowe_slowa[i]<<endl;
}
}
int main()
{
polowa();
return 0;
}

int polowa() promises to return an int, but the return keyword is conspicuously absent from the function.
Looking over the code, you never use more than one element at a time. Odds are good you could rewrite this function to use no arrays and only one loop. – user4581301
You don't have to separate reading input and print output. Arrays are not needed. Proposed implementation:
#include <iostream>
#include <string>
int main()
{
unsigned tests;
std::cin >> tests;
while (tests--)
{
std::string word;
std::cin >> word;
std::cout << word.substr(0, word.length() / 2) << "\n";
}
}

According to Dessus proposition I wanted to make this code as a function called in int main(). But SPOJ can't accept me this code (when i am compiling this in code blocks, everythings okay).
#include <iostream>
#include <string>
std::string nowe_slowo(int t)
{
while (t--)
{
std::string word;
std::cin >> word;
std::cout<<word.substr(0, word.length() / 2)<<"\n";
}
}
int main()
{
unsigned tests;
std::cin >> tests;
nowe_slowo(tests);
}

Related

Why does for loop takes only the last string in this simple code?

I am a beginner in c++.
I will get to the point.I want to print out even-indexed and odd indexed letters of some strings.
Example :string "Hello"should be printed like "Hlo el".
but in this code if i choose 2 strings, the code only takes the last one.
I hope you understand me.Sorry for bad English.
int main() {
string S;
int T;
cin>>T;
for (int a=0;a<T;a++){
cin>>S;
}
for (int a=0;a<=S.length();a+=2){
cout<<S[a];
}
for (int c=1;c<=S.length();c+=2){
cout<<S[c];
}
}
Note: I want to enter all the strings first.That's why I didn't include the other two loops in the first one.
You have to store all strings in a container like vector
#include <iostream>
#include <string>
#include <vector>
int main() {
int T;
std::cin >> T;
std::vector<std::string> Ss(T);
for (auto &S : Ss){
std::cin>>S;
}
for (const auto &S : Ss) {
for (std::size_t a=0;a<=S.length();a+=2){
std::cout<<S[a];
}
for (std::size_t c=1;c<=S.length();c+=2){
std::cout<<S[c];
}
}
}

c++ How to read from a file into array one word at a time

I know this is a dumb question!
But I just CAN NOT get my head around how to read my file into an array one word at a time using c++
Here is the code for what I was trying to do - with some attempted output.
void readFile()
{
int const maxNumWords = 256;
int const maxNumLetters = 32 + 1;
int countWords = 0;
ifstream fin;
fin.open ("madLib.txt");
if (!fin.is_open()) return;
string word;
while (fin >> word)
{
countWords++;
assert (countWords <= maxNumWords);
}
char listOfWords[countWords][maxNumLetters];
for (int i = 0; i <= countWords; i++)
{
while (fin >> listOfWords[i]) //<<< THIS is what I think I need to change
//buggered If I can figure out from the book what to
{
// THIS is where I want to perform some manipulations -
// BUT running the code never enters here (and I thought it would)
cout << listOfWords[i];
}
}
}
I am trying to get each word (defined by a space between words) from the madLib.txt file into the listOfWords array so that I can then perform some character by character string manipulation.
Clearly I can read from a file and get that into a string variable - BUT that's not the assignment (Yes this is for a coding class at college)
I have read from a file to get integers into an array - but I can't quite see how to apply that here...
The simplest solution I can imagine to do this is:
void readFile()
{
ifstream fin;
fin.open ("madLib.txt");
if (!fin.is_open()) return;
vector<string> listOfWords;
std::copy(std::istream_iterator<string>(fin), std::istream_iterator<string>()
, std::back_inserter(listOfWords));
}
Anyways, you stated in your question you want to read one word at a time and apply manipulations. Thus you can do the following:
void readFile()
{
ifstream fin;
fin.open ("madLib.txt");
if (!fin.is_open()) return;
vector<string> listOfWords;
string word;
while(fin >> word) {
// THIS is where I want to perform some manipulations
// ...
listOfWords.push_back(word);
}
}
On the suggestion of πάντα ῥεῖ
I've tried this:
void readFile()
{
int const maxNumWords = 256;
int const maxNumLetters = 32 + 1;
int countWords = 0;
ifstream fin;
fin.open ("madLib.txt");
if (!fin.is_open()) return;
string word;
while (fin >> word)
{
countWords++;
assert (countWords <= maxNumWords);
}
fin.clear();
fin.seekg(0);
char listOfWords[countWords][maxNumLetters];
for (int i = 0; i <= countWords; i++)
{
while (fin >> listOfWords[i]) //<<< THIS did NOT need changing
{
// THIS is where I want to perform some manipulations -
cout << listOfWords[i];
}
}
and it has worked for me. I do think using vectors is more elegant, and so have accepted that answer.
The suggestion was also made to post this as a self answer rather than as an edit - which I kind of agree is sensible so I've gone ahead and done so.
The most simple way to do that is using the STL algorithm... Here is an example:
#include <iostream>
#include <iomanip>
#include <iterator>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector<string> words;
auto beginStream = istream_iterator<string>{cin};
auto eos = istream_iterator<string>{};
copy(beginStream, eos, back_inserter(words));
// print the content of words to standard output
copy(begin(words), end(words), ostream_iterator<string>{cout, "\n"});
}
Instead of cin of course, you can use any istream object (like file)

Latter part of code somehow affecting former

I have this program:
#include <iostream>
#include <vector>
#include <map>
#include <string>
#include <sstream>
#include <algorithm>
int main(int argc, const char * argv[]) {
std::vector<int> task_scores;
int n;
std::cin >> n;
for(int i = 0; i < n; i++) {
int sc;
std::cin >> sc;
task_scores.push_back(sc);
}
std::map<std::string, std::vector<size_t>> student_solutions;
std::string command = "";
while(true) {
std::vector<std::string> tok_com;
getline(std::cin, command);
std::stringstream strstream(command);
std::string token = "";
while (getline(strstream, token, ' ')) {
std::cout << token;
tok_com.push_back(token);
}
if (tok_com[0] == "SOLVED") {
std::string name = tok_com[1];
int task = std::stoi(tok_com[2]);
if(std::find(student_solutions[name].begin(), student_solutions[name].end(), task) !=
student_solutions[name].end()) {
student_solutions[name].push_back(task);
}
}
}
return 0;
}
If you comment out if clause, then code works just fine. But if you don't, the code stops with EXC_BAD_ACCESS when trying to cout the token. How can this happen?
But if you don't, the code stops with EXC_BAD_ACCESS when trying to cout the token. How can this happen?
if (tok_com[0] == "SOLVED") {
// ^^^
requires that at least one value was actually stored into the tok_com vector within your loop before.
You should test for tok_com.empty() before dereferencing tok_com:
if (!tok_com.empty() && tok_com[0] == "SOLVED") {
// ^^^^^^^^^^^^^^^^^^^
// ...
}
What you're experiencing actually is undefined behavior varying from exploding fridges, little demons flying out from your nostrils or simply exceptions thrown by your debugging environment or operating system.

Reading data into a struct array from a file

I have an input file that looks like this
1 0 3
2 11 5
3 15 1
4 16 11
and a structure that looks like this
struct numb {
int numb1;
int numb2;
int numb3;
}
and I need to create an array of the struct so that each element of the array holds all three numbers. So
numbArray[0].numb1 == 1
numbArray[0].numb2 == 0
numbArray[0].numb3 == 3
numbArray[1].numb1 == 2
numbArray[1].numb2 == 11
and so on. I've gotten the hang of opening and closing files, finding how many lines there are in a file, and reading a single line from a file, but I do not know how to store individual elements from a line.
My program looks like this so far:
#include <iostream>
#include <fstream>
#include <string>
int main(int argc, char* argv[])
{
ifstream inFile(argv[1]);
int fileLength = 0;
std::string line;
while(std::getline(inFile, line))
{
++fileLength;
}
struct numb {
int numb1;
int numb2;
int numb3;
}
if(inFile.is_open())
{
for(unsigned i = 0; i <= fileLength; i++)
{
//What to do here?
}
}
}
Use getline when you don't have regular structure to the input and need to handle variation between lines. When your input file has regular structure (in this case, there are always three values per line), then simply use the stream extraction operators directly:
#include <iostream>
#include <vector>
struct group
{
int n1;
int n2;
int n3;
};
int main()
{
std::vector<group> groups;
while (std::cin)
{
group line;
line.n1 << std::cin;
line.n2 << std::cin;
line.n3 << std::cin;
groups.push_back(group);
}
}
Express your ideas directly in code as much as possible.
Note I've written the code assuming that the file is in the proper form. If there are too many or too few values per line, then the above code will be confused. However, it is best to code the simplest thing that could possibly work and worry about complexity when you need it. In your example you stated that the input file was well-formed, so there's no need to overcomplicate things.
I recommend using a std::stringstream for this:
#include <iostream>
#include <sstream>
#include <string>
#include <stdio.h>
#include <vector>
struct numb {
int numb1;
int numb2;
int numb3;
};
void populate(std::vector<numb>& my_numbs, std::string line) {
std::stringstream ss(line);
numb my_numb;
ss >> my_numb.numb1 >> my_numb.numb2 >> my_numb.numb3;
my_numbs.push_back(my_numb);
}
void output(const numb my_numbs) {
printf("%d %d %d\n", my_numbs.numb1, my_numbs.numb2, my_numbs.numb3);
}
int main(int argc, char* argv[]) {
ifstream inFile(argv[1]);
std::string line;
std::vector<numb> my_vect;
while(std::getline(inFile, line)) {
populate(my_vect, line);
}
for(size_t i = 0; i < my_vect.size(); ++i) {
std::cout << "my_vect[" << i << "]:";
output(my_vect[i]);
}
return 0;
}
std::stringstreams allow you to parse out data types from std::strings, you you just need to parse out 3 ints, which you can use with your struct. You then push the struct into your vector.
Here's the working ideone taking input from stdin.
You should probably be able to do something like this:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main(int argc, char* argv[])
{
ifstream inFile(argv[1]);
int fileLength = 0;
std::string line;
struct numb {
int numb1;
int numb2;
int numb3;
};
vector<vector<int>> sets;
int n1, n2, n3;
while (std::cin >> n1)
{
cin >> n2;
cin >> n3;
vector<int> vec;
vec.push_back(n1);
vec.push_back(n2);
vec.push_back(n3);
sets.push_back(vec);
}
numb * numbSet = new numb[sets.size()];
//Since the vectors data is continuous in memory just as the array of structs are
//you can just copy the data directly
for (int i = 0; i < sets.size(); i++)
{
std::memcpy(&numbSet[i], &sets[i][0], sizeof(numb));
}
}

C++ How do I read in a file, convert each word to lower case and then cout each word?

I am having trouble getting started with a program. I need to read in each word from a file, then convert it to lower case. I would like to std::cout each word after I find it. I assume I need to use Cstr() some how. I am guessing I should use something like
ofs.open(infile.c_str());
but how to lower case?
string[i] = tolower(string[i]);
then,
std::cout << string[i];
Thanks for the help.
Here is a complete solution:
#include <ctype.h>
#include <iterator>
#include <algorithm>
#include <fstream>
#include <iostream>
char my_tolower(unsigned char c)
{
return tolower(c);
}
int main(int ac, char* av[]) {
std::transform(std::istreambuf_iterator<char>(
ac == 1? std::cin.rdbuf(): std::ifstream(av[1]).rdbuf()),
std::istreambuf_iterator<char>(),
std::ostreambuf_iterator<char>(std::cout), &my_tolower);
}
I found the answer to my own question. I really didn't want to use transform, but that does work as well. If anyone else stumbles across this here is how I figured it out...
#include <iostream>
#include <string>
#include <fstream>
int main()
{
std::ifstream theFile;
theFile.open("test.txt");
std::string theLine;
while (!theFile.eof())
{
theFile >> theLine;
for (size_t j=0; j< theLine.length(); ++j)
{
theLine[j] = tolower(theLine[j]);
}
std::cout<<theLine<<std::endl;
}
return 0;
}
int main()
{
ofstream of("xyz.txt");
clrscr();
ifstream inf;
char line;
inf.open("abc.txt");
int count=0;
while(!inf.eof())
{
inf.get(line);
if(line>=65 && line<=123)
{
cout<<line;
line=line-32;
of<<line;
count++;
cout<<line;
}
}
cout<<count;
getch();
return 0;
}
First of all, unless this is something like a homework assignment, it's probably easier to process one character at a time rather than one word at a time.
Yes, you have pretty much the right idea for converting to lower case, with the minor detail that you normally want to cast the input to unsigned char before passing it to tolower.
Personally, I'd avoid doing explicit input and output, and instead do a std::transform with a pair of istream_iterators and an ostream_iterator for the result.