The following code is for printing the elements of a matrix in spiral order. The program works fine. The problem, however, is that the test compiler against which I'm checking the program, doesn't accept trailing white spaces at the end of the output. Could anyone give me some ideas as to how I can get around the last white space being added at the output?
#include <stdio.h>
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
string input;
int value;
int matrixA[10][10],matrixB[10][10],result[10][10];
int k=0,l=0,m=0,n=0;
int i=0,j=0;
cout<<"Enter first matrix:\n";
while(true)
{
//Read string from keyboard
getline(std::cin,input);
if(input.empty())
{
break;
}
//Parse string using sring stream
stringstream ss(input);
j=0;
while (ss >> value)
{
matrixA[i][j]=value;
j++;
if (ss.peek()==' ')
ss.ignore();
}
i++;
}
//Assign row and column length
k=i;
l=j;
cout<<"Enter second matrix:\n";
i=0;
while(true)
{
//Read string from keyboard
getline(std::cin,input);
if(input.empty())
{
break;
}
//Parse string using sring stream
stringstream ss(input);
j=0;
while (ss >> value)
{
matrixB[i][j]=value;
j++;
if (ss.peek()==' ')
ss.ignore();
}
i++;
}
//Assign row and column length
m=i;
n=j;
bool first=true;
if(l==m)
{
//Multiplication logic
for(i=0;i<k;i++)
{
for(j=0;j<n;j++)
{
result[i][j]=0;
for(int d=0;d<m;d++)
{
result[i][j]=result[i][j]+matrixA[i][d]*matrixB[d][j];
}
}
}
cout<<"The product is:\n";
//Display matrix result
for(i=0;i<k;i++)
{
for(j=0;j<n;j++)
{
cout<<result[i][0];
}
for(j=1;j<n;j++)
{
cout<<' '<<result[i][j];
}
cout << "\n";
}
}
else
{
cout<<"The two matrices have incompatible dimensions.\n";
}
return 0;
}
Sorry for the bad typing!
Related
I am working on a homework problem. However, I am not sure how to correct the problem I am facing. You can ignore most of the code, I have gotten the first half to work, just trying to figure out how to make the map work.
I have tried this bad piece of coding.
stringstream ss(str);
map<string, int> words;
int arrayLength;
arrayLength = str.length();
string userarray[arrayLength];
for (int i=0;i<arrayLength;i++){
string tempString;
ss>>tempString;
userarray[i] = tempString;
words[userarray[i]]=i+1;
if(words[userarray[i]]==1)
{
words.insert(make_pair(userarray[i],i++));
}
cout<< words.at(userarray[i]);
}
This is all of my code
#include <algorithm>
#include <string>
#include <iostream>
#include <set>
#include <fstream>
#include <sstream>
#include <unordered_set>
#include <map>
#include <utility>
using namespace std;
int word()
{
{
//str store the string
string again = "y";
string str= "",checkStr;
cout<<"Enter the line : ";
getline(cin,str);
checkStr = str;
checkStr[str.length()-1]=' ';
while(again =="y")
{
//store all the tokens
set<char> tokens;
unordered_set<char> token;
//if characters are not in range consider as token
for (int i=0;i<str.length();i++)
{
char inChar = str[i];
if(inChar>='A' && inChar<='Z' || inChar>='a' && inChar<='z' )
{
}
else
{
if(str[i]!=' ' && str[i]!='\n' )
tokens.insert(inChar);
token.insert(inChar);
str[i] = ' ';
}
}
//print the tokens
set <char> :: iterator pointer;
cout<<"tokens are : "<<endl;
for (pointer = tokens.begin(); pointer != tokens.end(); ++pointer)
{
cout<<*pointer<<" ";
}
cout<<endl;
//print the tokens
cout<<"unordered set: "<<endl;
for(auto it = token.begin(); it != token.end();it++)
cout<< *it<< " ";
cout<< endl;
//store string to stream
stringstream ss(str);
map<string, int> words;
int arrayLength;
arrayLength = str.length();
string userarray[arrayLength];
for (int i=0;i<arrayLength;i++){
string tempString;
ss>>tempString;
userarray[i] = tempString;
words[userarray[i]]=i+1;
if(words[userarray[i]]==1)
{
words.insert(make_pair(userarray[i],i++));
}
cout<< words.at(userarray[i]);
}
cout<<"Press 'y' to run again: "<<endl;
getline(cin,again);
if(again =="y")
{
return 1;
}
else
{
cout<<"Function terminated"<<endl;
exit(2);
}
}
}
}
int main ()
{
while (word()==1)
{
word();
}
while(word()==2)
{
break;
}
}
My problem is that when I cout the code, I get a long list of numbers.
However, if I enter
"Have a good day. Have a good class. “+” Have a good visit. Have fun!”
I want the output to look like
have 4
a 3
good 3
day 1
class 1
visit 1
fun 1
I have since gotten my code to work, my friend helped me with the last bit today. The code is...
stringstream ss(str);
map <string,int> dict;
map <string,int> dict_counted;
string line;
// create an array of strings
string array[100];
int counter = 0;
while (getline(ss,line,' '))
{
array[counter] = line;
counter++;
if (dict.count(line))
{
dict[line]+=1;;
}
else
{
dict[line] = 1;
}
}
for (int i=0;i<counter;i++)
{
if (dict_counted.count(array[i]))
{
}
else
{
if (!(array[i].empty()))
{
cout<<"The frequency of "<<array[i]<<" is "<<dict[array[i]] <<endl;
dict_counted[array[i]] = -1;
}
}
}
I changed your third for a little
for(int i = 0; i<arrayLength; i++)
{
string tempString;
ss >> tempString;
if (tempString.empty())
continue;
words[tempString] = tempString.length();
cout << tempString << " " <<words[tempString]<<" ";
}
So I just started learning C++ and My professor briefly went over Address (&) and Dereference (*) Operators. I'm not fluent in C++ but i have been searching around for parts and using common knowledge to combine into this code. It fails to build so Please Help!
Assignment- Write a program that keeps reading in strings of varied sizes. If an input string has length greater than one store it in a vector. When an input string has length one (a single character) you will output the string stored in your vector that has the first letter matching the input character. Keep doing this while you read string "quit".
#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string input;
char* output;
vector<string> name;
while (input != "quit") {
cin >> input;
if (input.length == 1) {
for (int i = 0; i < name.size; i++) {
output = &name[i].at(0);
if (input == output) {
cout << name[i];
}
}
}
else {
name.push_back(input);
}
}
//system("pause");
return 0;
}
#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string input;
vector<string> name;
cin >> input;
while (input != "quit") {
if (input.length() == 1) {
for (int i = 0; i < name.size(); i++) {
if (input[0] == name[i][0]) {
cout << name[i] <<endl;
}
}
}
else {
name.push_back(input);
}
cin >> input;
}
system("pause");
return 0;
}
I have problem with this question I don't know what is wrong with my code that I get Presentation Error every time I don't know what is the format of output can you help me to solve this question I am sorry that my code is a little confusing
here is the link of question http://sharecode.ir/section/problemset/problem/1208
#include <iostream>
#include <string>
#include <algorithm>
#include <cstdio>
using namespace std;
int main()
{
string temp=" ";
bool cheak3=false,cheak4=false;
int n,num;
cin>>n;
while(n != 0)
{
if(cheak4 == true)
cout<<endl;
cheak4=true;
cin>>num;
cheak3=false;
string cheak1,cheak;
while(1)
{
if(num ==-1)
break;
getline(cin,temp);
for(int i=0 ; i<temp.size() ; i++)
{
if(temp[i] != ' ')
cheak.push_back(temp[i]);
else
{
reverse(cheak.begin(),cheak.end());
cheak1+=cheak;
cheak.clear();
if(cheak3 == true)
cheak1.push_back(' ');
}
}
reverse(cheak.begin(),cheak.end());
cheak1+=cheak;
cheak.clear();
num--;
if(cheak3 == true)
{
cheak1.push_back(' ');
cout<<cheak1<<endl;
cheak1.clear();
}
cheak3=true;
}
n--;
}
}
I believe the tricky part is you should print a blank line between the output blocks.
Your code has too complicated logic! Here is my solution to this problem:
#include <iostream>
#include <string>
using namespace std;
int main() {
int N, lines;
string word;
cin>>N;
while (N--) {
cin>>lines;
while (lines--) {
char end;
do {
cin >> word;
end = cin.get();
for (int i=word.length()-1;i>=0;i--) cout<<word[i];
cout << end;
} while (end != '\n');
}
if (N) cout << endl;
}
return 0;
}
The line if (N) cout << endl; makes sure you print a newline character for every output block except the last one (when N equals to 0).
After reading each word in a line, you can use cin.get(); in order to determine the next character. If it is a space, then print it and read the next word. Else if it is a \n print it and go to next line! :)
#include <iostream>
#include <vector>
#include <cstring>
#include <fstream>
#include <string>
#include <cmath>
using namespace std;
vector<string> Letter;
float frequency1(string word)
{
float count=0.0;
for (int i=0;i<Letter.size();++i)
{
transform(word.begin(),word.end(),word.begin(),::tolower);
transform(Letter[i].begin(),Letter[i].end(),Letter[i].begin(),::tolower);
if (strcmp(word.c_str(),Letter[i].c_str())==0)
{
count+=1;
}
}
count=(count/Letter.size())*100;
if (count>=0.5)
{
return count;
}
else
{
return 0.0;
}
}
int main()
{
ifstream fin;
fin.open("frequent.txt");
if (fin.fail())
{
cout<<"Error opening file!"<<endl;
}
while(!fin.eof())
{
string buffer;
getline(fin,buffer,' ');
cout<<buffer<<endl;
Letter.push_back(buffer);
}
cout<<endl;
vector<string> frequent;
vector<float> frequency;
for (int i=0;i<Letter.size();++i)
{
string a=Letter[i];
int k=0;
for (int j=0;j<i;++j)
{
transform(a.begin(),a.end(),a.begin(),::tolower);
transform(Letter[j].begin(),Letter[j].end(),Letter[j].begin(),::tolower);
if (a==Letter[j])
{
break;
}
k++;
}
int size=Letter.size();
if (k!=size-1)
{
continue;
}
float counter=frequency1(a);
if(counter>0.0)
{
frequent.push_back(Letter[i]);
frequency.push_back(counter);
}
}
cout<<"Here are the repeated words"<<endl;
for (int i=0;i<frequency.size();++i)
{
cout<<" "<<frequent[i]<<", frequency: "<<frequency[i]<<endl;
}
system("PAUSE");
return 0;
}
I am writing a program which determines the frequency of the repeated words in a document(text). If frequency is greater or equal to 0.5, the word passes as a repeated words. but when I run it, it doesn't show me any repeated word although I even calculated manually and know that there are repeated words in the document. I can't figure out the problem.
First, you should exit or wrap the remainder of main into an else, when you cannot open your input file
if (fin.fail())
{
cout<<"Error opening file!"<<endl;
}
Otherwise, you'd go on and try to read from an invalid stream.
You read your words with std::getline and a blank ' ' as delimiter. This means, that you include newlines '\n', tabs '\t', etc. in your words, which might not be what you intended. A better, and safer, approach to read your words, would be
std::string word;
while (fin >> word) {
// process word
}
This skips all whitespace and detects EOF properly as an added benefit.
There might be further problems as well.
I need to write a program where it takes 2 integers from a file. Then it has to make a pyramid from those 2 numbers. It has to look like this:
I've wrote the code and it works as I want to, bet I can't think of a way how make it look a pyramid like.
Here's how it looks when I do it:
And this is my code:
#include <fstream>
using namespace std;
int main(){
ifstream inFile("Duomenys.txt");
ofstream outFile("Rezultatai.txt");
int N,M,smth,suma=0;
inFile >> N >> M;
smth=N;
while(N<=M){
for(int i=smth;i<=N;i++){
outFile<<i<<" ";
suma+=i;
if(i==N){
for(int i=N-1;i>=smth;i--){
outFile<<i<<" ";
suma+=i;
}
}
}
outFile<<endl;
N++;
}
outFile<<endl<<"Skaiciu suma: "<<suma;
inFile.close();
outFile.close();
return 0;
}
So my question would be, how to make it that my answer would be shaped in pyramid like in example?
#include <fstream>
#include <iostream>
#include <iomanip>
#include <assert.h>
using namespace std;
template <class T>
int numDigits(T number)
{
int digits = 0;
while (number) {
number /= 10;
digits++;
}
return digits;
}
int main()
{
ifstream inFile("Duomenys.txt");
ofstream outFile("Rezultatai.txt");
int N,M,smth,suma=0;
inFile >> N >> M;
smth=N;
// assuming positive numbers
assert(N>=0 && M>=0);
// this will be the size of each printed number
int nd = numDigits<int>(M)+1;
while(N<=M){
for(int i=N;i<=M;i++)
outFile << setw(nd) << " ";
for(int i=smth;i<=N;i++){
outFile << setw(nd) << i;
suma+=i;
if(i==N){
for(int i=N-1;i>=smth;i--){
outFile << setw(nd) << i;
suma+=i;
}
}
}
outFile<<endl;
N++;
}
outFile<<endl<<"Skaiciu suma: "<<suma;
inFile.close();
outFile.close();
return 0;
}
First you must compute your second number's digit count. It's so easy. Then you can calculate the depth of concluded pyramid using: (second number- first number)+1. After that you can be sure that in the last row, the max digit count you will have is ((second number - first number)*2+1)*digit count=x of pyramid's head. So you should print the head of pyramid at (x,y)=(x of pyramid's head, ....)
To determine the length of the last row you can either write your output to an std::stringstream and get the length with myStrStream.str().size() (and afterwards print the contents of your string stream to std::cout or your outFile) or you can count the length of all items of the last line separately and then sum then up, including spaces. I think the first approach is simpler.
The easiest approach might be backtracking.
This also depends on the digits that every number have.
Assuming that every number has two digits, is enough to add a certain number of space for each iteration.
This number in your case is 5 during the first iteration, and ends up being zero:
#include <fstream>
using namespace std;
int main(){
ifstream inFile("Duomenys.txt");
ofstream outFile("Rezultatai.txt");
int N,M,smth,suma=0;
inFile >> N >> M;
smth=N;
while(N<=M){
for(int i=smth;i<=N;i++){
outFile<<i<<" ";
suma+=i;
if(i==N){
for(int i=N;i<M;i++)
cout << " ";
for(int i=N-1;i>=smth;i--){
outFile<<i<<" ";
suma+=i;
}
}
}
outFile<<endl;
N++;
}
outFile<<endl<<"Skaiciu suma: "<<suma;
inFile.close();
outFile.close();
return 0;
}
An alternative is to use iomanip's setw, but this case you have to write all numbers in a string and print the whole string each time.
#include<fstream>
using namespace std;
ofstream outFile("output");
void printSpace(int a){
string spaces(a,' ');
outFile<<spaces;
}
int main(){
int N=1,M=11,smth=4,suma=0;
int l=2*(M-N);
while(N<=M){
printSpace(l);
for(int i=smth;i<=N;i++){
outFile<<i<<" ";
suma+=i;
if(i==N){
for(int i=N-1;i>=smth;i--){
outFile<<i<<" ";
suma+=i;
}
}
}
l-=2;
outFile<<endl;
N++;
}
outFile<<endl<<"Skaiciu suma: "<<suma;
outFile.close();
return 0;
}
inFile >> N >> M;
smth=N;
while(N<=M){
for(int position=0;position<(M-N);position++){ // doesn't work if M<N obviously
for(int digit=(smth+position);digit;digit=digit/10){
outFile<<" ";
}
outFile<<" "; // this is to complement the spacer for each digit in your code
}
for(int i=smth;i<=N;i++){
outFile<<i<<" ";
...