小编Pau*_*lP1的帖子

为什么strlen与s的大小不同,为什么cout char显示的是字符而不是数字?

我写了一段代码来计算'e'一堆单词中有多少个字符.

例如,如果我输入"I read the news",那么e存在多少个的​​计数器应为3.

#include <iostream>
#include <cstring>
using namespace std;

int main()
{
    char s[255],n,i,nr=0;
    cin.getline(s,255);

    for(i=1; i<=strlen(s); i++)
    {
        if(s[i-1]=='e') nr++;
    }
    cout<<nr;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我有两个关于C++中字符的不清楚的事情:

  1. 在上面的代码中,如果我strlen(s)用255 替换,我的代码就不起作用了.我只能输入一个单词,程序就会停止.我在学校被教过strlen(s)这个字符串的长度s,在这种情况下,就像我宣称的那样,是255.那么,为什么我不能只输入255而不是strlen(s)

  2. 如果我正常运行上面的程序,它不会显示一个数字,就像它应该做的那样.它向我展示了一个角色(我相信它来自ASCII表,但我不确定),就像一颗心或一颗钻石.它应该e从单词中打印出的数字.

有人可以向我解释这些吗?

c++ ascii character

5
推荐指数
1
解决办法
182
查看次数

指针保留字符串

所以我写了一个输入一个单词的代码,把它的第一个字母放在单词的末尾(例如"egg"将是"gge",如果我们再次执行相同的过程,它将是"geg"和然后终于回到"鸡蛋")我想只做一次这个过程.我想用一个指针记住单词的初始值,即egg,然后字符串必须记住"gge".

这是代码:

#include <iostream>
#include <cstring>
using namespace std;
int main()
{
    char s[100],aux,*P;
    int p=1,i,n,k,j;
    cin.get(s,100);
    i=0;
    while(i>=0)
    {
        P=s; //this is the pointer that SHOULD memorize "egg"
        aux=s[0]; 
        for(j=1; j<=n; j++) s[j-1]=s[j];
        s[n]=aux;//until here it does the letter thing
        break;
    }
     cout<<P<<endl<<s;//now here the pointer P should be "egg" and the string s should be "gge"
     //but the program prints out "gge" and "gge".

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我做错了什么,我该怎么做我想要的?

c++ string algorithm pointers

3
推荐指数
1
解决办法
73
查看次数

什么是打印此矩阵的if语句

我传递一个矩阵作为输入(c ++),我想打印出矩阵外部的数字,即它的"空心方形元素".我知道怎么做,这就是if语句:if(i==0 || i==n || j==0 || j==n).我想打印矩阵的下一帧,因为这个if语句打印矩阵的外框.我想要打印所有下一帧.

我已经使用矩阵的外部,if(i==0 || i==n || j==0 || j==n)但正如我所说,它打印矩阵的第一帧,我想打印下一帧.

例如,给定矩阵

1 2 3 4
4 3 2 1
5 6 7 8
8 7 6 5
Run Code Online (Sandbox Code Playgroud)

它应该打印:

3 2
6 7 
Run Code Online (Sandbox Code Playgroud)

所以它是"第二"框架,它是矩阵的内部.第一帧应该是:

1 2 3 4
4     1
5     8
8 7 6 5
Run Code Online (Sandbox Code Playgroud)

那么,我该如何打印下一帧呢?

c++ arrays matrix

2
推荐指数
1
解决办法
139
查看次数

标签 统计

c++ ×3

algorithm ×1

arrays ×1

ascii ×1

character ×1

matrix ×1

pointers ×1

string ×1