字符串不输出我键入的字符 [英] String not outputting the characters i type in

查看:57
本文介绍了字符串不输出我键入的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以该程序应该输入我输入的内容,并以矩阵格式输出它们,以下是我到目前为止的代码:

so this program is supposed to input things i type in, and output them in a matrix format, heres the code i have so far:

#include <iostream>
#include <string>

using namespace std;

#define N 6


//
// fill:
//
void fill(string s, int M[][N], int ROWS, int COLS)
{
int i, r, c;

for (i=0, r=0; r < ROWS; r++)
{
    for (c=0; c < COLS; c++)
    {
  M[r][c] = s[i];  // store ith character into matrix:

  i++;  // next character:
  if (i == s.length())  // start-over if that was last char:
    i = 0;
    }
}
 }

void print(int M[][N], int ROWS, int COLS)
{

string s;
getline(cin,s);
    int r, c;
for(r=0; r< ROWS; r++)
{
for(c=0; c < COLS; c++)
{


cout<<(char)M[r][c];


}

 cout <<endl; 
}
}
//
// main:
//
int main()
{
string s;
int  M[N][N];
int  M2[N][N];
int  row, col, ROWS, COLS;


ROWS = sizeof(M) / sizeof(M[0]);
COLS = sizeof(M[0]) / sizeof(M[0][0]);

fill(s, M, 1, 1);
print(M, ROWS, COLS);

return 0;
}

知道为什么它会输出随机字符而不是我输入的字符吗?

any idea why its outputting random characters out instead of the ones i type in?

推荐答案

尝试一下,

#include <iostream>
#include <string>

    using namespace std;

    #define N 6

    void fill(string s, char (&arr)[N][N])
    {
        int char_index =0;
        for (int i=0; i < N; i++)
        {
            for (int j=0; j < N; j++)
            {
                arr[i][j] = s.at(char_index);           
                if (char_index+1 == s.size()){
                    char_index =0;
                }else{
                    char_index++;
                }               
            }
        }   
    }

    void print(char arr[][N])
    {
        cout << "--------------" << endl;
        int char_index =0;
        for (int i=0; i < N; i++)
        {
            for (int j=0; j < N; j++)
            {
                cout << arr[i][j] << " ";
            }
            cout << endl;
        }
        cout << "--------------" << endl;

    }

    int main()
    {
        string s ="";
        cout << "Enter your string:";
        getline(cin,s); 
        char M[N][N];
        fill(s,M);
        print(M);
        system("pause");
        return 0;
    }

这篇关于字符串不输出我键入的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆