唯一的问题是,当一个文件位于EOF时,程序仍会写入-或+,只需要设置一些条件,使其仅在另一个文件处于EOF时才从一个文件中提取单词。例如
prvy.txt :Ahojte nasi studenti ktori maju radi programovanie
druhy.txt: vsetci mili
treti.txt: + Ahojte -vsetci + nasi -mili + studenti + ktori + maju + radi + programovanie
#include<stdio.h>
#include<stdlib.h>
int main(){
FILE *first, *second, *third;
char ch[256],ch1[256];
int i=1,count=0, ch2;
char space = ' ';
char minus = '-';
char plus = '+';
first=fopen("prvy.txt", "r");
second=fopen("druhy.txt", "r");
third=fopen("treti.txt", "w");
if(first==NULL || second==NULL || third==NULL)
{
perror("error");
exit(1);
}
while (fscanf(first, "%255s", ch) == 1)
{
count++;
}
while (fscanf(second, "%255s", ch) == 1)
{
count++;
}
printf("%d",count);
rewind(first);
rewind(second);
for(i;i<=count;i++)
{
if(i%2==1)
{
fputc(plus,third);
ch2=fgetc(first);
while(ch2 != EOF && ch2 != ' ' && ch2 != '\n') {
putc(ch2,third);
ch2=fgetc(first);
}
}
else if(i%2==0)
{
fputc(minus,third);
ch2=fgetc(second);
while(ch2 != EOF && ch2 != ' ' && ch2 != '\n') {
putc(ch2,third);
ch2=fgetc(second);
}
}
putc(space,third);
}
fclose(first);
fclose(second);
fclose(third);
return 0;
}
答案 0 :(得分:2)
您的代码将在两个文件之间交替显示。这将不起作用,因为文件中可能包含不同数量的单词。
一种解决方案可能是在每个文件的一个变量中计算单词数。然后循环可能类似于:
<?php
include '../koneksi.php';
if(isset($_POST['submit_add'])){
$nama = $_POST['nama'];
$alamat = $_POST['alamat'];
$kamar_id = $_POST['kamar_id'];
$kota_id = $_POST['kota_id'];
$sql = "INSERT INTO penghuni (nama,alamat,kamar_id,kota_id) VALUES ('$nama','$alamat','$kamar_id','$kota_id')";
if(!$conn->query($sql))
die('Tambah Penghuni Gagal'.$sql);
else
header("Location: penghuni.php");
}
if(isset($_POST['submit_edit'])){
$id_old = $_POST['id_old'];
$kamar_id = $_POST['kamar_id'];
$kota_id = $_POST['kota_id'];
$nama = $_POST['nama'];
$alamat = $_POST['alamat'];
$sql = "UPDATE penghuni SET nama='$nama', alamat='$alamat', kamar_id='$kamar_id', kota_id='$kota_id' WHERE id='$id_old'";
if(!$conn->query($sql))
die('Update Penghuni Gagal'.$sql);
else
header("Location: penghuni.php");
}
// $id = $_GET['id'];
if(isset($_POST['submit_delete'])){
$id_old = $_POST['id_old'];
$sql = "DELETE FROM penghuni
WHERE id='$id_old';";
if (!$conn->query($sql))
die('Hapus Penghuni Gagal'.$sql);
else{
header("Location: penghuni.php");
exit();
}
}
?>
答案 1 :(得分:2)
您无需先扫描两个文件即可计数。而是创建一个包含两个输入文件的数组,并在阅读时使用索引在两个输入文件之间切换。轮到一个文件用尽时,扫描并打印另一个文件。
这样,您就无需同时控制两个文件的成功输入:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *in[2]; // Two alternating input files
FILE *out;
char line[80];
char prefix[] = "+-"; // Alternating signs, +/-
int index = 0; // index to in[] and prefix[]
in[0] = fopen("1.txt", "r");
in[1] = fopen("2.txt", "r");
out = fopen("3.txt", "w");
if (!(in[0] && in[1] && out)) {
perror("fopen");
exit(1);
}
while (fscanf(in[index], "%79s", line) == 1) {
fprintf(out, "%c%s ", prefix[index], line);
index = !index;
}
while (fscanf(in[!index], "%79s", line) == 1) {
fprintf(out, "%c%s ", prefix[!index], line);
}
fclose(in[0]);
fclose(in[1]);
fclose(out);
return 0;
}